For deployment purposes, I have set up my Django app in a Docker container. The setup works, and I am able to serve it using Gunicorn and Apache. However, I can’t seem to access my Postgresql database anymore. This database is running locally, and I have no problem accessing it when launching my Django app from outside the container.
But when I launch my app from inside the Docker container, all I get is this error:
django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5433 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
Clearly I am not the first one having trouble with this.
I have made sure that Postgresql is listening to external adresses, as stated here, so this shouldn’t be a problem.
I have also tried playing around with my Docker compose configuration file. Using network_mode=host
is not compatible with port bindings. Back in network_mode=bridge
, I have also tried as upvoted here :
extra_hosts:
- "host.docker.internal:host-gateway"
But it does not change anything, nor does replacing 127.0.0.1
with 172.17.0.0
in my Django .env file.
I am a bit at a loss here, so any insight would be appreciated. I have to say that I am new to Docker, so maybe I’m missing something obvious.
I’m working with Ubuntu 22.04, Docker 24.0, Django 4.2, Postgresql 14. Here is my really simple docker-compose.yml :
services:
web:
build: ./
command: gunicorn main.wsgi:application --bind 0.0.0.0:8000
ports:
- 8000:8000
env_file:
- ./main/.env
And a sample .env file :
DATABASE_NAME=db_name
DATABASE_USER=db_user
DATABASE_PASSWORD=password
DATABASE_HOST=127.0.0.1
DATABASE_PORT=port
Thanks by advance !
2
Answers
You’re on the right path by adding the extra hosts.
Point the DB to the host gateway config to make it work, you are still not in localhost.
Make sure to stop/restart docker compose so the env variable change will take effect.
You can do one thing. Login to your container with
docker exec -it
and runhostname -I
command and get the ip. Then in your localhost run commandhostname -I
. You should have an ip in a network with your container. Replace that inDATABASE_HOST
in your env file. Hope it helps!