A web application usually needs to reach a database or cache in another container. Container IP addresses can change when containers are recreated, so you should not write them into your configuration. Compose gives you names instead.
The default network
When you run docker compose up, Compose creates a network for the project, named after it with _default added. Each service joins that network, and Docker's built-in DNS resolves a service name to the address of its container.
services:
web:
image: nginx:alpine
ports:
- "8080:80"
cache:
image: redis:alpineFrom inside web, the name cache resolves:
docker compose exec web getent hosts cache172.18.0.2 cache cacheYour address and the exact name columns may differ. If DNS ideas are new to you, read the networking basics guide.
Container ports, not published ports
Services on the same network talk directly to each other's container ports. web reaches Redis at cache:6379 even though cache has no ports entry. Publishing a port is only needed when something outside that network, such as your browser, must connect.
Suppose a database service is published as "15432:5432". Other containers use db:5432. Programs on the host use localhost:15432.
Inside a container, localhost means that container itself. An application that tries localhost:6379 from web will not find Redis.
Separate networks
You can define your own networks to limit who can talk to whom:
services:
proxy:
image: nginx:alpine
networks: [front]
app:
image: nginx:alpine
networks: [front, back]
db:
image: redis:alpine
networks: [back]
networks:
front:
back:proxy can reach app, and app can reach db. proxy and db share no network, so proxy cannot resolve or reach db by name.
Try it
Start the two-service example, then run the getent command from web. Next, run docker compose exec cache redis-cli -h cache ping and expect PONG. Finally, put the two services on different networks, run docker compose up -d, and repeat the lookup. It should now print nothing.
Check your understanding
Service Discovery
All 3 sections · no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.