ProjectStack
python

ConnectionRefusedError: [Errno 111] Connection refused

Your Python script tried to connect to a server or port (database, API, web server) but the connection was refused. Nothing is listening on that host and port combination.

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

  1. Start the required service: sudo systemctl start postgresql (or the relevant service)
  2. Verify the host and port in your config or .env file
  3. Test connectivity: telnet localhost 5432 or nc -zv localhost 5432
  4. 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 refused

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