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.
? What do the diagram colours mean
key idea / Docker itselfcontainer / good pathhost / watch outproblem / blockedneutral
The IP address trap
How a request finds its target
Networks as walls
bridge there is no DNS at all. Chapter 10 shows the DNS server behind the names, and chapter 13 shows why the default bridge never got one.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
Answer: Network membership: the database is only on backend-net.
The frontend is only on frontend-net. With no shared network there is neither a route nor a DNS name.
Why is hard-coding a container’s IP address in config a bad idea?
Show answer
Answer: Addresses are assigned at start and can change when the container is recreated.
After a restart or recreate the container may get a different address. Use its name on a shared network.