← Debugging Guides

阅读中文版本

Docker Compose — service cannot resolve another service name

Fix Compose service resolution by placing services on a shared network with matching names and correct references.

beginnerdebuggingdockercompose

Symptoms

  • Could not resolve host: db
  • The app connects to localhost instead of the service name
  • It works in one Compose file but not another
  • A service started by Compose cannot see another

Possible causes

  • The services are on different networks
  • The client uses localhost instead of the service name
  • The service name changed but references were not updated
  • An external network is expected but not defined

Diagnosis steps

List networks and attached services

docker compose ps ; docker network inspect <project>_default

Interpretation

The network membership shows which services share a network and can resolve each other by name.

Test resolution from inside the container

docker compose exec app getent hosts db

Interpretation

If the name does not resolve, the services are not on the same network or the name is wrong.

Fix references to use service names

DB_HOST=db

Interpretation

Inside Compose, services reach each other by service name, not localhost, which points at the container itself.

Root cause

The client could not resolve the other service because the services were not attached to a shared network or the wrong hostname was used, so DNS inside the container had no record to return.

Fix

Attach services to a common network, reference peers by service name rather than localhost, and define any external network explicitly so all services join it.

Verify the fix

Rerun the stack and confirm the service resolves and connects, and confirm both services list the shared network.

Symptom walkthrough

A service fails to connect with a message like Could not resolve host for another service name. Inside Compose, service discovery uses a shared network and each service name resolves to its container. If the services are on different networks, or the client uses localhost instead of the service name, DNS has nothing to return and the connection fails before any port is reached.

Fix in practice

Attach the services to a common network, which Compose does by default for one file but not automatically across separate projects, and reference peers by their service name. If an external network is intended, define it explicitly and attach every participating service.

Verification

Rerun the stack and confirm the service resolves and connects, then confirm both services list the shared network. Successful name resolution and connection confirm the networking is aligned.

Diagnostic commands

Check the behavior with commands like these:

docker compose ps ; docker network inspect <project>_default
docker compose exec app getent hosts db
DB_HOST=db