无法从运行在docker容器中的spring应用程序连接到运行在windows主机上的postgresql db。我得到Error response from daemon: invalid IP address in add-host: "host.docker.internal"
docker-compose.yml
version: '3.8'
services:
spring-app-container:
image: spring-app:1
build:
context: ./
dockerfile: Dockerfile
ports:
- "50800:50800"
extra_hosts:
- "local:host.docker.internal"
environment:
- DATABASE_HOST=local
- DATABASE_USER=user
- DATABASE_PASSWORD=********
- DATABASE_NAME=psqldb
- DATABASE_PORT=5432
application.properties
## PostgreSQL
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/psqldb
spring.datasource.username=user
spring.datasource.password=******
在spring application.properties中将localhost作为url参数是否正确?
在postgresql.conf中,listen_addresses = '*'。这是否足以允许从容器中的spring应用程序连接?
我在stackoverflow:
上看到了这个方法IP_ADDRESS=$(ip addr show | grep "binetb.*bdocker0b" | awk '{print $2}' | cut -d '/' -f 1)
在docker-compose. conf文件的哪里可以添加这个命令?yml文件?
和docker-compose.yml
extra_hosts:
docker.host: ${IP_ADDRESS}`
Thanks in advance
终于可以连接到主机了
docker-compose.yml
version: '3.8'
services:
spring-app-container:
image: spring-app:1
build:
context: ./
dockerfile: Dockerfile
ports:
- "50800:50800"
environment:
- DATABASE_HOST=local
- DATABASE_USER=user
- DATABASE_PASSWORD=********
- DATABASE_NAME=psqldb
- DATABASE_PORT=5432
在主机上输入以下命令获取IP:
docker run busybox ping -c 1 host.docker.internal | awk 'FNR==2 {print $4}' | sed s'/.$//'
有了这些设置,它就可以工作了:)