Common causes
- The database, API server, or service your script depends on isn't running
- Wrong host or port — connecting to port 5432 when the database is on 5433
- The service is running but bound to a different network interface
- A firewall is blocking the connection
How to fix it
- Start the required service: sudo systemctl start postgresql (or the relevant service)
- Verify the host and port in your config or .env file
- Test connectivity: telnet localhost 5432 or nc -zv localhost 5432
- Check that the service is listening: ss -tlnp | grep 5432 (Linux)
Example
Traceback (most recent call last):
File "app.py", line 5, in <module>
conn = psycopg2.connect(host='localhost', port=5432, dbname='mydb')
ConnectionRefusedError: [Errno 111] Connection refusedConnecting to PostgreSQL from Python when the database server isn't running
Have a different error?
Paste any error message into the Error Translator to get an instant explanation.
