mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
281 words
1 minute
Docker Compose Network & DNS Troubleshooting: Why Can't Containers Connect?

One of the most common failures in Compose projects is “all containers have started, but services cannot access each other.” These types of problems usually center around networking, DNS, and startup sequences.

1. Three Highly Frequent Errors#

  1. connection refused
  2. temporary failure in name resolution
  3. no route to host

These errors might look similar, but their root causes are completely different.

2. Check the Network Topology First#

docker compose ps
docker network ls
docker network inspect <network_name>

Goal: Confirm whether the services are in the same compose network.

3. Service Name Resolution Rules#

Within a Compose network, services should access each other via service_name:port.

Incorrect example:

  • Connecting to the database B from inside container A by accessing localhost:5432.

Correct example:

  • Using db:5432 (where db is the service name).

4. depends_on Does Not Mean “Service Ready”#

depends_on only guarantees the startup order; it does not guarantee that the database is ready to accept connections.

It is recommended to add health checks and retry logic:

services:
app:
depends_on:
db:
condition: service_healthy
db:
healthcheck:
test: ["CMD", "pg_isready", "-U", "postgres"]
interval: 5s
timeout: 3s
retries: 10

5. The Difference Between Port Mapping and In-Container Access#

  • ports is used for “Host <-> Container” mapping.
  • Inter-container access does not rely on ports; it relies on the internal network.

Many people mistakenly believe that without port mapping, containers cannot communicate with each other. This is a typical misconception.

6. Quick Diagnostic Commands#

Execute inside the container:

getent hosts db
nc -vz db 5432
curl -I http://api:8080

These three steps can quickly determine whether the issue lies with DNS, ports, or the service itself.

7. Common Fixes#

  1. Unify services under the same user-defined network.
  2. Change cross-container access addresses to service names.
  3. Add health checks to dependent services.
  4. Add a startup retry mechanism on the application side.

Summary#

The essence of Compose network failures is often a “faulty mental model.” As long as you thoroughly understand that “inside a container, localhost only points to itself,” you can locate 80% of cross-access problems on the first try.

Share

If this article helped you, please share it with others!

Docker Compose Network & DNS Troubleshooting: Why Can't Containers Connect?
https://blog.levifree.com/posts/docker-compose-network-dns-troubleshooting/
Author
LeviFREE
Published at
2025-12-08
License
CC BY-NC-SA 4.0

Some information may be outdated

Table of Contents