[Solved]-Django can't connect to Postgres in Docker setup

11👍

Turns out the issue was that Postgres hadn’t fully spun up before starting the Django app. This was easily solved by waiting a few seconds before starting the web server. I set the command for my web service to ./bin/boot.sh, and the contents of that file are:

#!/bin/sh

# wait for Postgres to start
sleep 10

python manage.py migrate

python manage.py runserver 0.0.0.0:8000

Edit

This method might not be good enough depending on your application – sleeping for 10 seconds works for me, most of the time, but it’s possible that postgres will take 11 seconds to spin up. Here’s an improved bash file, with a function I took from this example.

#!/bin/bash

# wait for Postgres to start
function postgres_ready(){
python << END
import sys
import psycopg2
try:
    conn = psycopg2.connect(dbname="postgres", user="postgres", password="postgres", host="postgres")
except psycopg2.OperationalError:
    sys.exit(-1)
sys.exit(0)
END
}

until postgres_ready; do
  >&2 echo "Postgres is unavailable - sleeping"
  sleep 1
done

python manage.py migrate

gunicorn pft.wsgi:application -w 2 -b 0.0.0.0:8000 --reload

0👍

I had this problem and it was only because I was using a VPN. If you are using something like sshuttle just turn it off.

Leave a comment