Django cannot connect to PostgreSQL: connection refused on port 5432, locally or in Docker
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refusedShort answer
Connection refused means nothing accepted the connection at the host and port Django used. Find out whether PostgreSQL is listening, then compare the host and port in DATABASES with where it really is. Inside Docker Compose, use the database service name and the container port, never localhost or the published host port.
Fix it fast
1Find out which cause you have
From the same place Django runs (the host, or inside the web container), test the exact host and port from your settings.
pg_isready -h localhost -p 5432 # inside Docker: docker compose exec web pg_isready -h db -p 54322Match what you see, then jump to its fix
- 1
pg_isready reports no response on localhost:5432 even on the database machinePostgreSQL is not running, or listens on a different portFix - 2
Connection refused to localhost or 127.0.0.1 from inside the web container, while the host can reach the database fineIn Docker, Django uses localhost, but the database is in another containerFix - 3
The error appears only at container start, then goes away on a restartThe database starts after Django, so the first connection is refusedFix - 4
Refused from another machine or container, but works on the database host with localhostPostgreSQL listens on loopback only, and the client is on another host or networkFix
- 1
What does the error look like?
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refusedIs the server running on that host and accepting TCP/IP connections?django.db.utils.OperationalError: connection refused
Cause 1 of 4
PostgreSQL is not running, or listens on a different port
1Check
The port setting defaults to 5432, and port and listen_addresses change only at server start. Check the service and which port it really bound.
sudo systemctl status postgresql
sudo ss -ltnp | grep postgres2Fix
Start the service and fix the error in its log if it does not stay up. If it uses another port, put that port in DATABASES.
sudo systemctl start postgresql
# settings.py
DATABASES["default"]["PORT"] = "5432"3Verify
pg_isready answers accepting connections.
pg_isready -h localhost -p 5432Confirmed by postgresql.org
Cause 2 of 4
In Docker, Django uses localhost, but the database is in another container
1Check
Inside the web container, localhost is the web container, which has no PostgreSQL. Compose gives each service a DNS name equal to its service name on the default network.
docker compose ps
docker compose exec web env | grep -i -E "DB_|DATABASE"2Fix
Set the host to the Compose service name, and use the container port 5432. The host port in a ports entry such as 8001:5432 is only for access from outside the network.
# docker-compose.yml
services:
db:
image: postgres:16
web:
build: .
environment:
DB_HOST: db
DB_PORT: "5432"
# settings.py
"HOST": os.environ["DB_HOST"], "PORT": os.environ["DB_PORT"],3Verify
Restart and check the connection from the web container.
docker compose up -d
docker compose exec web pg_isready -h db -p 5432Confirmed by docs.docker.com
Cause 3 of 4
The database starts after Django, so the first connection is refused
1Check
depends_on without a health condition only orders container start; it does not wait until PostgreSQL accepts connections. Read the db log for the ready line and compare times.
docker compose logs db | tail -n 202Fix
Give the db service a healthcheck with pg_isready and make web wait for it.
services:
db:
image: postgres:16
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
retries: 10
web:
depends_on:
db:
condition: service_healthy3Verify
Bring the stack up from scratch and watch web start after db is healthy.
docker compose down && docker compose upConfirmed by docs.docker.com
Cause 4 of 4
PostgreSQL listens on loopback only, and the client is on another host or network
1Check
listen_addresses defaults to localhost, which allows only loopback connections. Anything outside the host is refused.
sudo -u postgres psql -c "SHOW listen_addresses;"2Fix
Add the interface PostgreSQL should listen on, restart (a reload is not enough), then allow the client's subnet in pg_hba.conf and reload.
# postgresql.conf
listen_addresses = 'localhost,10.0.0.5'
# pg_hba.conf
host all all 10.0.0.0/24 scram-sha-2563Verify
Restart, reload and test from the client.
sudo systemctl restart postgresql
psql -h 10.0.0.5 -U myuser -d mydb -c "SELECT 1;"Confirmed by postgresql.org
How do I stop it coming back?
- Read host and port from environment variables, with the Compose service name in the container.
- Use a healthcheck so dependent services wait for a ready database.
- Keep PostgreSQL off public interfaces; allow only the subnets that need it.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Databases
A Postgres query in Docker fails with: could not resize shared memory segment
ERROR: could not resize shared memory segment: No space left on device
Postgres in a container hands query memory to parallel workers through the container's /dev/shm.
2 causes, each with a fixDatabases
The Postgres container refuses to start: data directory has invalid permissions
mkdir: cannot create directory ‘/home/postgres/pgdata/data’: permission denied
Postgres starts only when its data directory is owned by the server user and closed to everyone else: mode 0700, or 0750 when group read is enabled.
3 causes, each with a fixDatabases
The Postgres container cannot set permissions on a bind-mounted data folder
chmod: changing permissions of '/var/lib/postgresql/data': Operation not permitted
Postgres needs its data directory owned by the server user with mode 0700.
3 causes, each with a fixDatabases
DBeaver cannot run pg_restore: the utility is not found in the client home
Utility 'pg_restore' not found in client home '/usr/lib' (/usr/lib)
DBeaver runs pg_restore from a local PostgreSQL client folder; it does not bundle one.
3 causes, each with a fixDatabases
manage.py test stops with 'permission denied to create database' on PostgreSQL
django.db.utils.ProgrammingError: permission denied to create database
Django creates a separate database called test_ plus your database name, using the DATABASES USER.
2 causes, each with a fixDatabases
An EC2 instance cannot reach its RDS database
Could not open connection to the host, on port <port>: Connect failed
RDS denies all access until a security group allows it.
3 causes, each with a fix