2

I'm a beginner at docker and new to docker-compose. I am trying to get a project running with docker compose. When My backend app tries to connect to the db, I get this error:

org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

Can you see anything wrong with my compose file that could cause it to not connect?

version: "3"

services:
  db:
    image: postgres
    volumes:
      - data-volume:/var/lib/db
    ports:
     - "5432"
  backup:
    image: ubuntu
    volumes:
      - data-volume:/var/lib/backup/data
  backend:
    image: java
    restart: always
    volumes:
      - data-volume:/var/lib/backup/data
      - ~/code/myCode:/usr/src/app/
    command: sh /usr/src/app/Docker/docker-setup.sh
    expose:
      - "8000"


volumes:
  data-volume:
1
  • Shouldn't you map the container port to the host port like this - "5432:5432"? Commented May 25, 2017 at 22:32

1 Answer 1

3

Your db is not in the localhost of your Java container. You can point in your Java configuration to Postgres as this: db:5432 Also you can a link from your Java container to db to start in order:

backend:
    image: java
    links:
    - db
    (...the rest...)

Maybe you will need to wait that Postgres open its port 5432 before Java starts (I don't know if it is mandatory). If you need that, the common way is to add a wait-for-it.sh script (available on GitHub), modifying the command:

command: /wait-for-it.sh db:5432 -- sh /usr/src/app/Docker/docker........

Sign up to request clarification or add additional context in comments.

3 Comments

You can also use depends_on to require that db has started before backend starts. docs.docker.com/compose/compose-file/#dependson
I thought that in docker-compose.yml files above version 2 the services are in the same network so they should not be explicitly linked.
Filtfilt, you're right. But expressing links give some startup order. Links also express dependency between services in the same way as depends_on, so they determine the order of service startup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.