-1

Can't connect to postgresql db which is running on windows host from a spring app which is running in a docker container. I get 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=******

Is it correct to have localhost as url parameter in the spring application.properties?

In the postgresql.conf, listen_addresses = '*'. Is this sufficient to allow the connection from spring app in the container?

I saw this approach on stackoverflow:

IP_ADDRESS=$(ip addr show | grep "\binet\b.*\bdocker0\b" | awk '{print $2}' | cut -d '/' -f 1)

Where can I add this command in the docker-compose.yml file?

and in the docker-compose.yml

extra_hosts:
  docker.host: ${IP_ADDRESS}`

Thanks in advance

midi
  • 3,128
  • 5
  • 30
  • 47
  • 1
    It seems like you already know about the [`host.docker.internal` special host name](https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach). That needs to get into the `spring.datasource.url` property; the easiest way is to set a `SPRING_DATASOURCE_URL` environment variable. Remove all of the network-related Compose settings, including `extra_hosts:` but especially `network: host` (which doesn't really work on Windows). – David Maze Jun 13 '22 at 11:09
  • I get "Error response from daemon: invalid IP address in add-host: "host.docker.internal"". I changed the post. – midi Jun 13 '22 at 11:18
  • On Windows, you shouldn't need to do any special setup for that at all - no `network_mode:`, no `extra_hosts:`, no `add_host:`. – David Maze Jun 13 '22 at 13:13
  • I did try without all mentioned parameters, but still not able to connect to my host from the container – midi Jun 13 '22 at 15:28

1 Answers1

0

Finally I'm able to connect to the host.

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

On the host type this command to get the IP:

docker run busybox ping -c 1 host.docker.internal | awk 'FNR==2 {print $4}' | sed s'/.$//'

With these settings it works :)

midi
  • 3,128
  • 5
  • 30
  • 47