Connection refused by server
Production Risk
Common in service orchestration; implement retry with backoff for dependent services.
A subclass of ConnectionError (errno ECONNREFUSED) raised when a connection attempt is refused by the remote host — the target port is not listening.
- 1The target service is not running or not listening on the specified port
- 2A firewall is blocking the port
- 3Wrong host or port in the connection parameters
Connecting to a port where no server is listening.
import socket
s = socket.create_connection(('127.0.0.1', 9999))expected output
ConnectionRefusedError: [Errno 111] Connection refused
Fix
Verify the service is running and listening
WHEN When ConnectionRefusedError is raised
import socket
import time
def connect_with_retry(host, port, retries=5, delay=2):
for i in range(retries):
try:
return socket.create_connection((host, port), timeout=5)
except ConnectionRefusedError:
if i < retries - 1:
time.sleep(delay)
raise ConnectionRefusedError(f"Could not connect to {host}:{port}")Why this works
Retry with delay handles service startup races; check service status if retries fail.
import socket
socket.create_connection(("127.0.0.1", 9999)) # ConnectionRefusedErrortry:
conn = socket.create_connection((host, port), timeout=5)
except ConnectionRefusedError:
print(f"Nothing listening on {host}:{port}")import time, socket
for i in range(5):
try:
return socket.create_connection((host, port), timeout=5)
except ConnectionRefusedError:
time.sleep(2 ** i)✕ Hardcode localhost/port without fallback
Services may not be ready immediately after startup; implement retry logic in health checks.
Python Docs — Built-in Exceptions
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev