psycopg2 cannot connect: connection refused on port 5432
psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refusedShort answer
Connection refused means nothing accepted the connection at the address psycopg2 tried. It does not mean PostgreSQL rejected you. Check that the server runs, that it listens on the TCP address and port your DSN names, and that the client's host and port match the server's settings.
Fix it fast
1Find out which cause you have
Try the same host and port with psql, outside Python. If psql fails with the same message, the problem is the server or the address, not your code.
psql -h localhost -p 5432 -U postgres -d postgres2Match what you see, then jump to its fix
- 1
Connection refused on every attempt, from every clientThe server is not running, or is not listening on that portFix - 2
Connection refused for a remote host or a Docker or VM address, while localhost works on the server itselfThe server accepts connections on a different address than the client usesFix - 3
The server works with psql on its own machine, but the Python app is refused, or the message mentions a Unix socket pathThe client host and port are not what you think they areFix
- 1
What does the error look like?
psycopg2.OperationalError: 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?connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory
Cause 1 of 3
The server is not running, or is not listening on that port
1Check
PostgreSQL's own start-up documentation calls this the generic 'could not find a server to talk to' failure. Look for a process listening on the port you use, and read the server log for a start-up error.
ss -ltn | grep 5432
psql -h localhost -p 5432 -U postgres -c "SHOW port;"2Fix
Start the server and fix whatever stopped it from starting (the log names it). If the server runs on another port, put that port in the DSN. The port is a start-up setting, so changing it in postgresql.conf needs a restart.
# postgresql.conf
port = 54323Verify
psql connects, then so does Python.
psql -h localhost -p 5432 -U postgres -c "SELECT 1;"
python -c "import psycopg2; print(psycopg2.connect('host=localhost port=5432 user=postgres dbname=postgres').closed)"Confirmed by postgresql.org
Cause 2 of 3
The server accepts connections on a different address than the client uses
1Check
listen_addresses defaults to localhost, which allows only local loopback TCP connections. A client on another machine is refused until the server also listens on a reachable address.
psql -h localhost -U postgres -c "SHOW listen_addresses;"2Fix
Set listen_addresses to the interface the clients reach (or '*' for all), and restart the server because it can only be set at start.
# postgresql.conf
listen_addresses = '*'3Verify
From the client machine, connect to the server's address.
psql -h 203.0.113.10 -p 5432 -U postgres -d postgresConfirmed by postgresql.org
Cause 3 of 3
The client host and port are not what you think they are
1Check
If host is empty, libpq uses a Unix-domain socket on Linux and macOS, and localhost only on Windows. A host that starts with a slash is a socket directory. An empty port means the built-in default. Print what the app actually passes.
python -c "import os; print(os.environ.get('DATABASE_URL'), os.environ.get('PGHOST'), os.environ.get('PGPORT'))"2Fix
Name both host and port in the connection string, and for a socket make the directory match the server's unix_socket_directories setting.
import psycopg2
conn = psycopg2.connect(host="127.0.0.1", port=5432,
dbname="appdb", user="app", password="secret")3Verify
The connection opens and reports itself as not closed.
python -c "import psycopg2; print(psycopg2.connect(host='127.0.0.1', port=5432, dbname='appdb', user='app', password='secret').closed)"Confirmed by postgresql.org
How do I stop it coming back?
- Keep the host and port in one environment variable or DSN and read it from one place.
- Test a new database address with psql before you put it in the app.
- Write listen_addresses and port into configuration management so a restart does not undo them.
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:
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
- MenuloA restaurant discovery platform in Germany, kept current by a Python ingestion pipeline.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Databases
psql or pgAdmin gets Connection refused from a Postgres container
Is the server running on that host and accepting TCP/IP connections?
Connection refused means nothing accepted the connection at the address and port you used.
4 causes, each with a fixDatabases
python manage.py migrate finishes but the tables for my app are missing
relation "myapp_book" does not exist
migrate only applies migration files that exist.
3 causes, each with a fixDatabases
Django save fails on PostgreSQL: null value in a column violates a not-null constraint
django.db.utils.IntegrityError: null value in column "price" of relation "shop_product" violates not-null constraint
A model field is NOT NULL in the database unless it has null=True.
3 causes, each with a fixDatabases
Django migration on PostgreSQL stops with 'pending trigger events'
django.db.utils.OperationalError: cannot ALTER TABLE "mytable" because it has pending trigger events
PostgreSQL runs a Django migration in one transaction.
2 causes, each with a fixDatabases
psycopg2 cannot resolve the host name db in Docker Compose
could not translate host name "db" to address
Compose registers each service in its own DNS under the service name, but only containers on the same Compose network can look it up.
4 causes, each with a fixDatabases
InFailedSqlTransaction: commands ignored until end of transaction block
SQLSTATE 25P02 (in_failed_sql_transaction)
Some earlier statement in the same transaction failed, and PostgreSQL ignores everything after it until you roll back.
3 causes, each with a fix