Django unable to connect to PostgreSQL Docker container using hostname (WSL)
I'm facing an issue where my Django application, running on Windows Subsystem for Linux (WSL), can't connect to a PostgreSQL database running in a Docker container.
The error I'm getting in Django is:
django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known
I'm starting the PostgreSQL container using the following Docker command:
docker run --name postgres -p 5432:5432 -e POSTGRES_PASSWORD=postgres -d postgres
And this is my environment varaible in django:
DATABASE_URL=postgres://postgres:postgres@postgres:5432/postgres
How can I fix this?
Just change URL (write localhost:5432):
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres
Because you run django application in WSL and PostgreSQL container in Docker on host machine so, django application will can't connect with 'PostgreSQL' by container name.
So, you can use the host machine's loopback IP address (127.0.0.1 or localhost)
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres
or the IP address of the host machine on the local network (view via ipconfig command).
Look like:
DATABASE_URL=postgres://postgres:postgres@192.168.x.x:5432/postgres