Skip to content
Latchkey

redis-py "redis.exceptions.ConnectionError: Error connecting to Redis" in CI

The Python redis-py client tried to open a socket to your configured host and port and the connect() failed. The wrapped errno 111 (Connection refused) means the Redis service container is not reachable at that address in CI.

What this error means

A pytest run or app boot raises "redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection refused." from inside the redis package during the first command or ping.

python
redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379.
Connection refused.

Common causes

Wrong host between runner job and container job

A job on the runner host reaches Redis at localhost with a mapped port; a job running inside a container reaches it by the service name (redis) on the Docker network, not localhost.

The client connected before the service was ready

redis-py connects lazily on first use, so a test that runs before the service health check passes hits a refused socket.

How to fix it

Point the client at the address CI actually exposes

  1. On a runner-host job, use localhost and the mapped port.
  2. On a container job, use the service name as the host.
  3. Read the address from an env var so tests do not hard-code it.
conftest.py
import os, redis
r = redis.Redis(
    host=os.environ.get("REDIS_HOST", "localhost"),
    port=int(os.environ.get("REDIS_PORT", "6379")),
)
r.ping()

Set the host per job type

For a container job, set REDIS_HOST to the service name so redis-py resolves it on the container network.

.github/workflows/ci.yml
env:
  REDIS_HOST: redis
  REDIS_PORT: '6379'

How to prevent it

  • Read the Redis host and port from environment, never hard-code localhost.
  • Wait for the service health check before the first redis-py call.
  • Match the host to the job model (runner host vs container network).

Frequently asked questions

What causes ""redis.exceptions.ConnectionError""?
A job on the runner host reaches Redis at localhost with a mapped port; a job running inside a container reaches it by the service name (redis) on the Docker network, not localhost.
How do I fix "redis.exceptions.ConnectionError"?
Point the client at the address CI actually exposes

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card