Docker Compose Containers Can't Reach Each Other

Compose services talk over a shared network using service names as hostnames. Connection failures mean you are on different networks or using the wrong name.

What you'll see

Root causes

Services declared in different compose files / networks

docker-compose creates a default network per project directory. Two compose projects do not share one unless you define an external network.

Wrong hostname

The hostname is the service key (the name under services:), not the container_name, not the image name.

Depends_on without healthcheck

depends_on only orders startup, it does not wait for the database to accept connections. The app crashes on first boot.

Fix it

  1. Confirm both containers share a network
    docker network inspect <project>_default | grep -B2 Container
  2. Test name resolution from inside the app container
    docker compose exec app getent hosts db
  3. For cross-file networking, define a shared external network
    networks:
      shared:
        name: shared
        external: true
  4. Add a healthcheck so depends_on waits properly
    db:
      healthcheck:
        test: ["CMD", "pg_isready", "-U", "postgres"]
        interval: 5s
    app:
      depends_on:
        db:
          condition: service_healthy

Field note

Never point one compose service at another using localhost — inside a container, localhost is the container itself.

Common questions

Why can't my containers reach each other by name?

They're on different networks, or you're using the wrong name: compose service names are only resolvable within a shared user-defined network. Same compose file defaults to one network; separate compose projects need an explicit shared network.

Why does localhost not work between containers?

Each container has its own network namespace: localhost inside container A is container A, never container B. Use the service name (http://api:3000) — Docker's embedded DNS maps it to the right container IP.

Ship it right the first time

A production-shaped compose stack: healthchecks, resource limits, log rotation. Never debug a boot race again.

Docker Production Starter — $19 →

One-time. Yours to modify. Instant download from the NinjaOps template store.