CalcSnippets Search
Redis 2 min read

How to Fix Redis Connection Refused in Docker Compose When the Container Looks Up but the App Still Cannot Connect

A practical guide to fixing Redis connection refused errors in Docker Compose by checking service names, startup timing, exposed ports, network context, and whether the application is trying to reach localhost from inside another container.

Why this issue fools people: Redis can be perfectly healthy while your app still fails, because the app is pointing to the wrong hostname, starting too early, or trying to use localhost from inside a container.

The error usually looks like:

ECONNREFUSED 127.0.0.1:6379

or:

Error 111 connecting to localhost:6379. Connection refused.

The first thing to understand

If your app runs inside Docker Compose, localhost means that same container, not the Redis container. That is the mistake behind a huge share of these failures.

A correct minimal Compose setup

services:
  app:
    build: .
    depends_on:
      - redis
    environment:
      REDIS_HOST: redis
      REDIS_PORT: 6379

  redis:
    image: redis:7
    ports:
      - "6379:6379"

Notice the hostname: redis, not localhost.

Step 1: confirm the Redis container is actually healthy

docker compose ps
docker compose logs redis
docker compose exec redis redis-cli ping

If redis-cli ping returns PONG, Redis itself is fine.

Step 2: confirm the app container can resolve the service name

docker compose exec app getent hosts redis

If name resolution fails, the containers may not be on the same Compose network.

Step 3: check startup timing

Some apps try to connect before Redis is ready. In that case, the fix is not changing hostnames forever. It is adding retries or health-aware startup behavior.

Example pattern in application code:

for (let i = 0; i < 10; i++) {
  try {
    await client.connect();
    break;
  } catch (err) {
    await new Promise((r) => setTimeout(r, 2000));
  }
}

Step 4: separate host-machine access from container-to-container access

  • From your laptop to Redis: localhost:6379 can be correct if the port is published
  • From app container to redis container: use redis:6379

Mixing those two contexts creates fake mysteries.

Verification sequence

docker compose exec redis redis-cli ping
docker compose exec app env | grep REDIS
docker compose logs app

You want:

  1. PONG
  2. host set to redis
  3. app logs without connection refusals

Bottom line

When Redis says “connection refused” in Compose, first debug container networking, hostnames, and startup order. Most of the time Redis is not down. Your app is just knocking on the wrong door.

Sources

Keep reading

Related guides