user1298426
user1298426

Reputation: 3717

docker-compose - Not able to connect to postgres db

I am trying to run the docker-compose command on Jenkins slave but it fails while running the command pytest tests/integration. The command run integration tests with backend as postgres. Dockerfile is

version: "3.4"
services:
  test:
    build:
      context: ../..
      dockerfile: Dockerfile
    depends_on:
      - postgres_db
    environment:
      PG_UNITTEST_DB: "postgresql://testuser:testpassword@postgres_db/testdb"
    command: pytest tests/integration
  postgres_db:
    image:  postgis/postgis
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PASSWORD: testpassword
      POSTGRES_USER: testuser
      POSTGRES_DB: testdb

And the error I am getting is

psycopg2.OperationalError: could not connect to server: Connection refused
 Is the server running on host "postgres_db" (172.19.0.2) and accepting
 TCP/IP connections on port 5432?

I tried exposing port 5432 in docker-compose file in postgres_db section but didn't help. The same code works fine locally. The command I run is

docker-compose -f tests/integration/docker-compose.yml up --build --exit-code-from test

Upvotes: 0

Views: 556

Answers (2)

Muhammad Hasan
Muhammad Hasan

Reputation: 168

You need to define the order of starting the service so that your postgres container is up before the test container. For detailed info, you can refer to the docs: https://docs.docker.com/compose/startup-order/

Upvotes: 1

larsks
larsks

Reputation: 312400

Postgres takes a moment to start up before it can start servicing requests. It is likely that your code in the test container is attempting to connect before Postgres is ready.

Your best option is probably to add some retry logic to your integration test. E.g., add something to yoursetup method that loops until it is able to establish a successful database connection.

Upvotes: 1

Related Questions