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


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:


# wait for Postgres to start
sleep 10

python manage.py migrate

python manage.py runserver


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.


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

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

python manage.py migrate

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


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