[Django]-Docker connection error for PostGIS and Django

4πŸ‘

βœ…

It’s most likely a timing issue: your application is trying to connect to the database before the database is ready. The easiest solution here is probably to just set a restart policy on your application container, so that docker will restart it when it fails. You might as well get rid of the depends-on directive, because this is functionally useless: while docker knows when the database container is up, it knows nothing about the state of the database application itself.

  web:
    build: .
    command: bash -c "
        python manage.py makemigrations
        && python manage.py migrate
        && python manage.py runserver 0.0.0.0:8000
        "
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    restart: on-failure
      - db  web:
    build: .
    command: bash -c "
        python manage.py makemigrations
        && python manage.py migrate
        && python manage.py runserver 0.0.0.0:8000
        "
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    restart: on-failure

An alternative solution is to put a script into your application container that explicitly waits for the database to respond before starting up the web application.

The problem with this solution is that you may want to be able to restart the database container (for example, to upgrade to a newer version of postgres), in which case your application will probably fail again, unless it has reconnect logic built in. Using the restart policy is probably the better choice.

πŸ‘€larsks

Leave a comment