ConnectionRefusedError: What It Means and How to Fix It
Error reference
ConnectionRefusedError
Language
Severity
HighWhen it happens
ConnectionRefusedError is raised when a TCP connection attempt is actively rejected by the target host.
Potential fixes
Verify the target service is running and listening on the expected port. Implement retry logic with exponential backoff for services that may not be ready immediately. Check firewall rules and ensure the port number in your configuration matches the server.
Related errors
Deep dive
ConnectionRefusedError is raised when a TCP connection attempt is actively rejected by the target host. This means the host is reachable but no process is listening on the specified port. It is a subclass of ConnectionError and OSError.
Why it happens
- •The target service (database, web server, etc.) is not running.
- •The service is running but on a different port than specified.
- •A firewall is blocking the connection and sending a TCP RST packet.
- •The server process crashed or has not finished starting up yet.
Potential fixes
Verify the target service is running and listening on the expected port. Implement retry logic with exponential backoff for services that may not be ready immediately. Check firewall rules and ensure the port number in your configuration matches the server.
Examples
Code that triggers the error
import socket
s = socket.create_connection(("localhost", 9999))Error output
ConnectionRefusedError: [Errno 111] Connection refused
Fixed code
import socket
try:
s = socket.create_connection(("localhost", 9999))
except ConnectionRefusedError:
print("Server is not running on port 9999")Practice in English
How would you explain a ConnectionRefusedError to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free