Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Databases and Redis

Django cannot connect to PostgreSQL: connection refused on port 5432, locally or in Docker

Errorconnection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused

Short 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.

  • Applies to PostgreSQL 16, Django 5.2, psycopg 3, Docker Compose v2, Ubuntu 24.04
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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 5432
  2. 2Match what you see, then jump to its fix

    1. 1pg_isready reports no response on localhost:5432 even on the database machinePostgreSQL is not running, or listens on a different portFix
    2. 2Connection 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. 3The error appears only at container start, then goes away on a restartThe database starts after Django, so the first connection is refusedFix
    4. 4Refused 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

What does the error look like?

  • connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
  • Is 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 postgres

2Fix

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 5432

Confirmed by postgresql.org

Did this fix it?

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 5432

Confirmed by docs.docker.com

Did this fix it?

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 20

2Fix

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_healthy

3Verify

Bring the stack up from scratch and watch web start after db is healthy.

docker compose down && docker compose up

Confirmed by docs.docker.com

Did this fix it?

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-256

3Verify

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

Did this fix it?

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

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.