Connecting to host database from a Docker container
Generally speaking, in a production environment, you don't want things like Nginx and your database running in Docker containers. You want those services running on the host and your application(s) in a container.
The tricky part here is that localhost
in a container is the container's network, not the host's. So postgres://user@localhost:5432/somedatabase
won't work.
Lots of solution online suggest using IP ranges or setting network=host
so that Docker uses the host network.
The best solution is to use volumes. The great think about Linux is pretty much everything is a file. So if something has a port, it probably has a socket.
So then your docker-compose.yml file can just look like this:
services:
web:
image: organisation/image-name
ports:
- "8000:8000"
volumes:
- /var/run/postgresql/:/var/run/postgresql/
Then away you go. For a Django app, you just set HOST="/var/run/postgresql"
in your settings file.