[Solved]-Docker Django could not connect to server: Connection refused

15👍

When those who have this problem please check your settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': 'db'
    }
}

Your HOST:'db' and docker-compose file db name should be same. If you want to rename from db, make sure that you change in docker-compose file and setting.py:

db:
  restart: always
  image: postgres:latest
  ports:
    - "5432:5432"
  volumes:
    - pgdata:/var/lib/postgresql/data/

1👍

Checkout your manage.py,
there should be a line

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

if there is no such line, put it

set your DJANGO_SETTINGS_MODULE with respect to PYTHONPATH.

UPD i cloned your repo and launched the web service by changing command in docker-compose.yml

-  command: /usr/local/bin/gunicorn docker_django.wsgi:application -w 2 -b :8000
+  command: python manage.py runserver 0.0.0.0:8000

I’m sure DJANGO_SETTINGS_MODULE is correct.

👤suhain

0👍

I’m exactly facing the same issue, while runing my django app with docker on aws ec2 instance.

I noticed that this error only happend for the first time the docker image is build, so to fix i juste ran :

CTRL + C then docker-compose up again and everything worked fine.

Leave a comment