patterndockerMajor
Docker Compose services communicate via service name, not IP or localhost
Viewed 0 times
compose networkingservice discoverydnsbridge networkservice namehostname
Error Messages
Problem
Containers in the same Compose project can't connect to each other using localhost or hardcoded IPs. Connections time out or are refused.
Solution
Docker Compose creates a default bridge network and registers each service name as a DNS entry. Services connect using the service name as the hostname:
Here
services:
db:
image: postgres:16
app:
image: myapp
environment:
DATABASE_URL: postgres://user:pass@db:5432/mydbHere
db resolves to the db container's IP automatically.Why
Compose creates a user-defined bridge network with an embedded DNS server. Container names and service names are registered in that DNS, enabling service discovery without hardcoded IPs.
Gotchas
- Services on different Compose projects are on different networks and can't reach each other by default — use external networks
- The DNS name is the service name, not the container name (container_name overrides the container name but not the DNS alias)
- Using
network_mode: hostdisables the Compose network and breaks service-name DNS - Scale replicas (deploy.replicas) get round-robin DNS for the service name
Code Snippets
Service name DNS resolution in Compose
services:
redis:
image: redis:7-alpine
worker:
image: myworker
environment:
REDIS_URL: redis://redis:6379 # 'redis' is the service name
app:
image: myapp
environment:
REDIS_URL: redis://redis:6379
# NOT redis://localhost:6379Context
Multi-container Docker Compose setups where services need to communicate
Revisions (0)
No revisions yet.