Docker container getting connection refused from postgres container in docker-compose

Viewed 334

I've been beating my head against this for a few days now and I'm finally asking for help after trying to find the solution myself from all over.

I have a docker-compose file that looks like this:

services:
   db:
      image: ...
      container_name: db
      ports:
         - "8095:5432"
      networks:
         - mynetwork
   springservice:
      image: ...
      container_name: springservice
      depends_on:
         - db
      ports:
         - "8090:8090"
      networks:
         - mynetwork
      environment:
         - SPRING_DATASOURCE_URL: jdbc:postgresql://db:8095/dbname
         - SPRING_DATASOURCE_USER: user
         - SPRING_DATASOURCE_PASSWORD: password
networks:
   mynetwork:
      driver: bridge
      name: mynetwork

Postgres has to be put to another port because we've got 3 postgres containers in that compose, so each get their own port.

Postgres's listen_address is set to "*". pg_hba is set with "host all 0.0.0.0/0 md5"

Both containers come up, but when I curl from the service container to http://db:8095/ , I get connection refused.

What am I missing here?

1 Answers

Your port mapping is meaningless inside the docker network. This is only a mapping to the host system. Inside the network, the container is always available on its native port.

 - SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/dbname

Also note that you don't need to publish the port to access it from inside the network. Doing so for a database can impose security risks. If you can, you should not publish it. That way, it will be only accessible from inside the docker network.

Related