Container-to-container communication
Containers must find each other by name, and you decide who may talk to whom by choosing which networks they join.
key idea / Docker itselfcontainer / good pathhost / watch outproblem / blockedneutral
The IP address trap
How a request finds its target
Networks as walls
Default bridge versus user-defined
| Feature | Default bridge | User-defined network |
|---|---|---|
| Name resolution | No, IP only | Yes, container name |
| Isolation | All containers share one network | You group containers |
| Set up | automatic | docker network create |
| Attach a running container | no | docker network connect |
Try it yourself
Build the three-tier layout from the diagram and prove the wall works.
-
Step 1 · Two networks and the database
$ docker network create frontend-net $ docker network create backend-net $ docker run -d --name db --rm --network backend-net alpine:3.20 sleep 300 -
Step 2 · The api starts on one network, then joins the second
network connectadds a second endpoint, so the api can see both sides.$ docker run -d --name api --rm --network frontend-net alpine:3.20 sleep 300 $ docker network connect backend-net api $ docker run -d --name web --rm --network frontend-net alpine:3.20 sleep 300 -
Step 3 · web reaches api by name, not db
$ docker exec web ping -c 1 api 64 bytes from 172.18.0.3: seq=0 ttl=64 $ docker exec web ping -c 1 db ping: bad address 'db' -
Step 4 · api reaches db
$ docker exec api ping -c 1 db 64 bytes from 172.19.0.2: seq=0 ttl=64 $ docker stop web api db $ docker network rm frontend-net backend-net
Recap
- Container IPs change; names do not. Always address containers by name.
- Name lookup works only on user-defined networks.
- A request is: DNS lookup, then veth to the bridge, then forward to the target veth.
- Two containers can talk only if they share a network. That is your first line of defense.
Quick check
The frontend can ping the API but not the database. Which single setting explains this?
Show answer
Network membership. The database is only on backend-net, the frontend only on frontend-net. With no shared network there is neither a route nor a DNS name.