Docker Compose — Network & DNS Issues

1 minute read

Troubleshoot service discovery, DNS resolution, and network connectivity in Docker Compose.

Service Not Found (DNS)

ping: bad address 'api'

Common Causes

  1. Different networks — services must share a network:
services:
  web:
    networks: [frontend]
  api:
    networks: [backend]     # web can't reach api!

Fix: Put both on a shared network.

  1. Service not running:
docker compose ps          # Is the service up?
  1. Using container name instead of service name:
# Wrong: ping myapp-api-1
# Right: ping api

Test DNS Resolution

docker compose exec web nslookup api
Server:    127.0.0.11
Address:   127.0.0.11#53

Name:      api
Address:   172.20.0.3

Connection Refused

connection refused

Check the Service is Listening

docker compose exec api netstat -tlnp
# or
docker compose exec api ss -tlnp

Common Causes

Cause Fix
App listening on 127.0.0.1 Bind to 0.0.0.0
Wrong port Check container port, not host port
Service not ready Add health check + depends_on

Critical: Apps inside containers must listen on 0.0.0.0, not 127.0.0.1.

Network Inspect

# List all project networks
docker network ls | grep myapp

# Inspect a network
docker network inspect myapp_default

Cross-Service Communication

Between services, always use the container port, not the host port:

services:
  api:
    ports:
      - "8080:3000"     # Host:Container
From host:      curl http://localhost:8080
From container: curl http://api:3000        ← use container port!

DNS Cache Issues

Docker’s embedded DNS server (127.0.0.11) usually handles this, but if you see stale DNS:

docker compose restart     # Forces DNS refresh

Debug Network with a Test Container

docker compose exec api sh -c "apk add --no-cache curl && curl -v http://db:5432"

Or add a debug service:

services:
  debug:
    image: alpine
    command: sleep 3600
    networks:
      - frontend
      - backend
    profiles: [debug]
docker compose --profile debug up -d debug
docker compose exec debug ping api
docker compose exec debug nslookup db

Summary

Problem Diagnosis Fix
DNS failure nslookup <service> Share a network
Connection refused ss -tlnp in container Bind to 0.0.0.0
Wrong port Check host vs container port Use container port internally
Stale DNS Restart services docker compose restart

Quick Reference

Item Detail
DNS Services must share a network
Bind address App must listen on 0.0.0.0
Internal port Use container port between services
Debug DNS docker compose exec nslookup
Inspect docker network inspect