Skip to content
Latchkey

Memcached "Connection refused" on port 11211 in CI

The client could not open a socket to Memcached on 11211: connection refused. As with Redis, this is a readiness or addressing problem in CI, the memcached service container is still starting, the port is not published, or the host is wrong for the job model.

What this error means

A test that connects to Memcached fails with "Connection refused" or "Error connecting to localhost:11211" while the service container is still booting.

memcached
pymemcache.exceptions.MemcacheServerError: (b'localhost:11211',
'Connection refused')
# or from telnet/nc:
localhost [127.0.0.1] 11211 (?) : Connection refused

Common causes

Memcached service not ready yet

The container is created before memcached is listening, so an early client connect is refused.

Unmapped port or wrong host

A runner-host job needs the port published to reach localhost:11211; a container job must use the service name on the Docker network.

How to fix it

Wait for the port to open

Poll the port with nc before running tests so the first connection is not refused.

Terminal
for i in $(seq 1 30); do
  nc -z localhost 11211 && break
  echo "waiting for memcached..."; sleep 1
done

Publish the port and set the host

Map 11211 for a runner-host job, or use the service name on a container job.

.github/workflows/ci.yml
services:
  memcached:
    image: memcached:1.6
    ports: ['11211:11211']

How to prevent it

  • Gate tests behind a port readiness check for Memcached.
  • Publish 11211 for runner-host jobs; use the service name in container jobs.
  • Externalize the Memcached host/port so tests are portable.

Frequently asked questions

What causes "Memcached "Connection refused" 11211"?
The container is created before memcached is listening, so an early client connect is refused.
How do I fix Memcached "Connection refused" 11211?
Poll the port with nc before running tests so the first connection is not refused.

Related guides

References

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