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.
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
- On a runner-host job, use localhost and the mapped port.
- On a container job, use the service name as the host.
- Read the address from an env var so tests do not hard-code it.
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.
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).