ConnectionRefusedError
PythonERRORNotableConnection ErrorHIGH confidence

Connection refused by server

Production Risk

Common in service orchestration; implement retry with backoff for dependent services.

What this means

A subclass of ConnectionError (errno ECONNREFUSED) raised when a connection attempt is refused by the remote host — the target port is not listening.

Why it happens
  1. 1The target service is not running or not listening on the specified port
  2. 2A firewall is blocking the port
  3. 3Wrong host or port in the connection parameters
How to reproduce

Connecting to a port where no server is listening.

trigger — this will error
trigger — this will error
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

Verify the service is running and listening
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.

Code examples
Triggerpython
import socket
socket.create_connection(("127.0.0.1", 9999))  # ConnectionRefusedError
Handle with try/exceptpython
try:
    conn = socket.create_connection((host, port), timeout=5)
except ConnectionRefusedError:
    print(f"Nothing listening on {host}:{port}")
Avoid with retry and health checkpython
import time, socket
for i in range(5):
    try:
        return socket.create_connection((host, port), timeout=5)
    except ConnectionRefusedError:
        time.sleep(2 ** i)
What not to do

Hardcode localhost/port without fallback

Services may not be ready immediately after startup; implement retry logic in health checks.

Sources
Official documentation ↗

Python Docs — Built-in Exceptions

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors