Identify the network path first
Containers in a Compose project commonly reach one another on a shared network. An app connecting to a database usually targets the Compose service name and its container port—not localhost and not the host-published port. This is a general troubleshooting note; the actual network depends on the Compose file.
Check that both services share a network
docker compose ps
docker compose config
docker network ls
docker compose config expands the configuration. Review its output before sharing it; secrets may have been written directly into the file. Confirm both services are running and attached to at least one common network. Custom network settings can change the defaults.
Test DNS and TCP from the client container
Run the checks from the client container. If the image lacks diagnostic tools, use a temporary troubleshooting container on the same network; do not expose a database port publicly just to debug it.
docker compose exec app getent hosts db
docker compose exec app sh -c 'nc -vz db 5432'
Replace db and 5432 with the real service name and listening container port. If the name resolves but the port refuses connections, inspect the database listen address, health state and startup timing. depends_on alone does not always mean the service is ready.
Common traps
- Inside a container,
localhostrefers to that container. - With
ports: "15432:5432", another container normally usesdb:5432; a host tool uses the published port15432. - Separate Compose projects normally have separate networks; service names do not resolve across them automatically.
References
Record the same connection test before and after a change. If publishing a port appears to fix it, also check whether that exposed more of the service than intended.