database connection_error ai_generated true

psycopg2.OperationalError: could not connect to server: Connection refused

ID: database/connection-refused

Also available as: JSON · Markdown
93%Fix Rate
95%Confidence
85Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
16 active

Root Cause

PostgreSQL server is not running or not listening on the expected host/port. Most commonly caused by the service being stopped, misconfigured listen_addresses, or firewall rules blocking port 5432.

generic

Workarounds

  1. 93% success Start the PostgreSQL service and verify it is listening on the correct port
    Run 'sudo systemctl start postgresql' (or 'pg_ctl start -D /var/lib/postgresql/16/main'). Verify with 'ss -tlnp | grep 5432' or 'pg_isready -h localhost -p 5432'.
  2. 88% success Check and update listen_addresses in postgresql.conf to bind to the correct interface
    Edit postgresql.conf and set listen_addresses = '*' (or the specific IP). Restart PostgreSQL. Also ensure pg_hba.conf allows connections from the client IP.

Dead Ends

Common approaches that don't work:

  1. Reinstalling the PostgreSQL client library (psycopg2) to fix the connection error 95% fail

    The error is a server-side connectivity issue, not a client library bug. Reinstalling psycopg2 does not affect whether the PostgreSQL server is reachable.

  2. Changing the connection string encoding or SSL mode without verifying the server is actually running 90% fail

    If the server process is not running or not listening on the target port, no amount of connection parameter tweaking will establish a connection.

Error Chain

Leads to:
Preceded by:
Frequently confused with: