1

I am trying to run a simple Django app with PostgreSQL using docker-compose. The PostgreSQL container runs fine and is accessible but I am unable to reach it from inside the Django container using python.

Here is my docker-compose.yaml:

version: "3"
services:
  db:
    image: "postgres"
    restart: always
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql/data

  django:
    build: ./qc_django
    ports:
      - "8080:8080"
    environment:
      - DB_NAME=django
      - DB_USER=${DB_USER}
      - DB_PASSWORD=${DB_PASSWORD}
      - DB_HOST=db
      - DB_PORT=5432
      - DEBUG=True
    depends_on:
      - db

volumes:
  pgdata:

Here are the database settings inside of the Django settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': env("DB_NAME"),
        'USER': env("DB_USER"),
        'PASSWORD': env("DB_PASSWORD"),
        'HOST': env("DB_HOST"),
        'PORT': env("DB_PORT"),
    }
}

The error it spits out after a minute or so:

django.db.utils.OperationalError: could not connect to server: Connection timed out
     Is the server running on host "db" (172.21.0.2) and accepting
     TCP/IP connections on port 5432?
Bitbart
  • 31
  • 3

2 Answers2

0

After rebooting and removing orphan containers with --remove-orphans my original configuration worked. Looks like there might have been some interference.

Bitbart
  • 31
  • 3
-1

You need to expose 5432 port for PostgresDB

As you mention, this is not mandatory anymore.

Your issue can throw because the PostgreSQL service is not started yet. So the port 5432 is not already listening. The depends_on parameter wait for the database container start, not for the database service.

You can follow this guide, they suggest putting a script that wait until the database service is launched, then start your Django application : https://docs.docker.com/compose/startup-order/

Xavier Brassoud
  • 697
  • 6
  • 14
  • 1
    I am still getting the same Error. To my knowledge the expose keyword is also not required and purely informative. See https://stackoverflow.com/a/65785558. – Bitbart Apr 29 '21 at 18:48
  • You've right. I think the port is not already exposed by PostgreSQL because the service is not already started. I will update my answer accordingly. – Xavier Brassoud Apr 29 '21 at 18:52
  • I used the wait-for-it.sh script and also implemented additional retries in the django application. Still no change, it always ends in the same Error. – Bitbart Apr 29 '21 at 19:53
  • 1
    I managed to solve the issue by removing orphan containers. Thanks for your suggestions though! – Bitbart Apr 30 '21 at 07:29