Lesson 140 ran one container. Real apps are several containers that talk: a web front, an API, a database, a cache. This lesson is the wires between them: bridge, host, none, overlay, custom networks, DNS by container name, port mapping, and the old --link flag and why networks replaced it. By the end you can put two containers on one network and have them find each other by name.
Difficulty: Advanced · Know this first: Lesson 140 — Docker from Scratch: Your First Image, Built and Run
Every hop charges rent in milliseconds. The bar below is a worked example for this lesson's scenario — not a measurement from a live system — but the shape is honest: on a cache hit the trip is almost free, on a miss the kitchen eats the budget. Step through the lesson or switch the scenario and watch the bar change.
Extra diagram · from scratch to master
Start with two strangers on one machine. Add one box at a time until the API finds the database by name.
The budget bar above shows three fixed stories. This simulator lets you write your own. Move a slider and watch the DNS lookups, the port mappings, and the bridge noise change in the budget bar, in the hop timings, and in the total. The numbers are a teaching example, not live measurements. The shape is the lesson: more containers on one shared network means more noise, and more networks mean fewer lookups each.
How many containers share this host. Every container adds DNS lookups and port mappings, and adds noise on a shared bridge.
How many networks the containers are split across. More networks mean fewer containers per network, and fewer lookups on each one.
How many ports are published to the host. Each one is a door to check, and two containers cannot share one host port.
Try this: (1) Set containers to 50, networks to 1, ports to 20. The DNS is about 50 min, the ports about 20 min, the bridge about 13 min, and the total is about 85 min. (2) Set containers to 2, networks to 10, ports to 1. The DNS is about 0 min, the ports about 1 min, the bridge about 1 min, and the total is about 4 min. Same host. Only the inputs changed.
Three questions. No score is saved anywhere — this is just you against the material.
Here is the network setup from this lesson, as a compose file, ready to edit. It puts the web and the database on one custom network, gives the database an alias, and publishes only the web port. Change it, then run the check.
Try breaking it on purpose: delete the networks block from the db service. Run the check and watch it fail. Then press Reset and try a change that keeps it passing, like adding a second alias for the database.
Expected output when it passes: The file has a networks block, a bridge driver, a database alias, and a published web port. The web finds the database by name on this network.
I take the same app four times here. First I learn the wires: bridge, custom network, DNS, port. Then I learn the isolation: one network per app. Then I learn the ends of the scale: none and overlay. Last I design a network for a real app.
Definition: A network connects containers. The default bridge network connects every container on the host, by IP address only. A custom network connects the containers on it, by name, through a DNS server Docker runs. A published port maps a host port to a container port, so a human outside can reach the app inside.
Types:
Uses: I use this to wire two containers together: create a network, run both containers on it, and have the web call the database by name. Try it now: edit the compose file in the Try it box so the database has a second alias, and run the check. Then practice the wiring in the Docker labs.
Dimensions: At low traffic everything is nearly free. What breaks first is the name: a typo in the container name, or two containers on two networks. It costs one docker inspect, which always shows the network the container is on.
Definition: A custom network is isolated by default. A container on app-net cannot reach a container on another network, even on the same host. One network per app keeps apps apart, and it keeps the database private: the API reaches it on the private network, and no published port is needed. A network alias lets one container answer to two names, so a new version can take over a name without the callers changing.
Types:
Uses: I use this when two apps share one host. I give each app its own network, publish only the web port, and leave the database private. Try it now: remove the ports block from the db service in the Try it box and run the check. The file still passes, and the database is safer for it. Then practice the split in the Docker labs.
Dimensions: As the apps grow, the networks grow, and the port map gets crowded. What breaks is the shared host port: two containers cannot take host port 3000. It costs a port plan, written down, before the third app lands on the host.
Definition: Host networking puts the container straight on the host network, with no isolation and no port mapping. None gives a container no network at all, which is the proof a job cannot talk to anything. Overlay spans many hosts, so containers on different machines share one network and find each other by name. The --link flag added one name to one container, in one direction, and networks replaced it because links do not scale.
Types:
Uses: I use host networking only when the app needs raw speed or a wide port range. I use none for a job that must not talk to anything. I use overlay when the app spans hosts. Try it now: change the driver in the Try it box from bridge to overlay and run the check. The check fails, because the lesson file uses bridge. The point is to see the driver is one word, and the word matters.
Dimensions: At ten times the hosts, the network is the system. What breaks is the flat network: every container on one bridge, every port mapped by hand, no names anywhere. It costs a network per app and a name per container, from the first day.
DNS is the test, not the ping. Two containers can ping each other by IP and still fail, because the app uses a name, not an IP. I test the name. I run a lookup for the database container by name from inside the app container, and I check that the name resolves to the right address. On the default bridge it does not resolve at all, and that is the finding. On a custom network it resolves, and that is the fix. The test is one command, and it settles the argument.
Try it: map container names to addresses from a sample inspect, and see which network resolves.
# python3 dns-check.py
containers = [("web", "172.18.0.3", "app-net"), ("db", "172.18.0.2", "app-net"), ("cache", "172.17.0.2", "bridge")]
for name, ip, network in containers:
resolves = network != "bridge"
print(name, ip, network, "->", "name resolves" if resolves else "NAME DOES NOT RESOLVE")
Expected: web and db resolve, cache on the default bridge does not. The fix is to move cache onto app-net, not to hardcode its IP.
Definition: At this level I design the network before I run the app: one network per app, a private network for the data tier that no web container joins, a published port only where a human calls in, and an overlay when the app spans hosts. I can draw the network on a whiteboard in a minute, and every line on it is a rule I can test: this container cannot reach that one, this port is the only door, this name resolves here and nowhere else.
Types:
Uses: I use this to review a setup I did not build: I ask which network each container is on, which ports are published, and which containers can reach the database. It is also how I teach the team: one whiteboard, one network per app, no exceptions. Try it now: draw the network for the app in the Try it box. If the database sits on the same network as the web, that is the first gap to close.
Dimensions: At a hundred times the containers, the network is not the bottleneck, the blast radius is. What breaks is the flat network that lets every container reach every other one. It costs a design, written down, with one network per tier.
Overlay is for many hosts, and the cost is real. A bridge network lives on one host. An overlay network spans many, and it pays for that with encapsulation: every packet gets wrapped, sent, and unwrapped. That costs latency and CPU, and it costs a control plane that must stay up. I use overlay only when containers on different hosts must talk, and I measure the latency before and after. A single-host app on an overlay is paying a tax for nothing.
Try it: compare the latency budget for bridge and overlay from a sample run.
# python3 overlay-cost.py
bridge_ms, overlay_ms = [0.4, 0.5, 0.4], [1.8, 2.1, 1.9]
print("bridge average (ms):", round(sum(bridge_ms) / len(bridge_ms), 2))
print("overlay average (ms):", round(sum(overlay_ms) / len(overlay_ms), 2))
print("overlay tax (ms):", round(sum(overlay_ms) / len(overlay_ms) - sum(bridge_ms) / len(bridge_ms), 2))
Expected: bridge about 0.43 ms, overlay about 1.93 ms, a tax of about 1.5 ms per call. At a thousand calls a second, that tax is real, and the multi-host need has to be worth it.
Start with the network commands from this lesson, run in order. Do this: run docker network create app-net, then docker run -d --name db --network app-net postgres:16, then docker run -d --name web --network app-net -p 3000:3000 myapp:1.0.0. Expected output: both containers join app-net, and the web reaches the database by the name db.
docker run --network, flag by flag. The network flag decides who the container can find by name. It is one flag, and it changes everything about the run.
-d runs the container in the background and prints its ID, then returns the prompt. Without it the terminal stays attached to the app, and closing the terminal stops the container.--name hello names the container. Without it Docker picks a random name, and every later command has to use the ID or that random name.--network app-net puts the container on the named network. Without it the container lands on the default bridge, where names do not resolve and the app cannot find the database by name.-p 3000:3000 publishes a container port on the host. The order is host port first, container port second. Without it the port stays private inside the container network, and nothing on the host can reach it.--rm removes the container when it stops. Without it the stopped container stays listed and keeps its name, so the next run with the same name fails with a name conflict.Flags you will meet next: --network host puts the container on the host network with no isolation, and --network none gives it no network at all.
Try it: run two containers on app-net and ping one by name from the other. It answers. Then run a third container with no --network flag and ping it by name. It does not answer. The flag is the difference.
docker network, flag by flag. The network commands are the whole lesson in four verbs: create it, join it, list it, and read it.
docker network create app-net makes the network. The name is the address the containers use to join it. Without the network, every container lands on the default bridge.docker network connect app-net stray adds a running container to a network. The container keeps its first network and gains a second one. It is the fix when two containers sit on different networks and cannot see each other.docker network ls lists the networks on the host. I run it when a name does not resolve, to see which networks exist and which one the container is on.docker network inspect bridge shows the network detail: subnet, gateway, and which containers are on it. The Containers block is where I find a container that landed on the wrong network.docker port web prints the published ports of a container. A container with no published port prints nothing, and that empty output is the answer: the container is private.Flags you will meet next: docker network create --driver overlay spans many hosts, --subnet picks the address range, and docker network connect --alias web2 gives a container a second name.
Try it: create app-net, run two containers on it, and ping one by name from the other. Then run docker network inspect app-net and read the Containers block. The two containers should both be listed there.
docker network create app-net
docker run -d --name db --network app-net postgres:16
docker run -d --name web --network app-net -p 3000:3000 myapp:1.0.0
docker run --rm --network app-net busybox nslookup db
docker run --rm --network app-net busybox ping -c 1 db
ping and nslookup, flag by flag. The app uses a name, not an IP. So I test the name, not the IP. These two commands are the test.
ping -c 1 db sends one packet and stops. Without -c it runs until I stop it. The name db is the test: on a custom network it resolves, and on the default bridge it does not.nslookup db asks the DNS server for the name db and prints the answer. Without a name there is nothing to look up. The app uses the name, not the IP, so the name is what I test.Flags you will meet next: ping needs a raw socket, which this VM does not allow, and a slim container may not have the ping binary at all. nslookup is the check that works in both places.
Try it: run both from inside a container on app-net, then from one on the default bridge. On app-net the name resolves and the ping answers. On the bridge the name does not resolve at all. That is the finding, and it is why the lesson uses a custom network.
What the snippet means: the first line makes the network, the next two lines put the containers on it, and the last two lines prove the name resolves. The nslookup prints the database IP. The ping answers by name. That is service discovery, and it is the whole lesson in five lines.
The default bridge is the diagnosis for a name that does not resolve. Do this: run docker run -d --name stray postgres:16 with no network flag, then docker run --rm --network app-net busybox ping -c 1 stray. Expected output: bad address. The stray container is on bridge. The tester is on app-net. Two networks, no shared DNS. Fix it with docker network connect app-net stray, and run the ping again. Expected output: the ping answers.
Port mapping is host port first, container port second, and the database needs none of it. Do this: run docker ps and read the PORTS column. Expected output: the web shows 0.0.0.0:3000->3000/tcp, and the database shows nothing. That empty column is the database being private. Then run docker port web. Expected output: 3000/tcp -> 0.0.0.0:3000. One door, named and visible.
docker ps, flag by flag. ps shows what is running. The flags decide whether the stopped ones show up, and which columns I read.
--filter "status=exited" shows only containers that match. Without it ps shows every running container, and the stopped one I am looking for is not in the list at all.--format "{{.Names}} {{.Status}}" prints only the fields I name, using a Go template. Without it I get the full table.Flags you will meet next: -a shows stopped containers too, and --format '{{.Names}} {{.Ports}}' prints names and ports only.
Try it: stop a container, then run docker ps. It is gone from the list. Run docker ps --filter status=exited and it appears. The container did not vanish. The default view just hides stopped ones.
A container can join more than one network, and that is how tiers are split. Do this: create a second network with docker network create data-net, connect the database to it with docker network connect data-net db, and run the API on both networks. Expected output: the API reaches the database on data-net, and the web cannot reach the database at all, because the web is only on app-net. That split is the design. Practice the split in the Docker labs.
At 10x the containers, the shape holds and the numbers grow. At 100x, the design changes: one network per app, one network per tier, and an overlay when the app spans hosts. The drivers never change. The discipline around them does. Lesson 144 is where the whole app lives in one file.
A container that fails to start because the port is taken is a failure I can find in five seconds with a check I run first. I try to bind the port from a small script before I start anything. If the bind fails, something is already there, and I find out what it is before I start the container, not after it crashes. The check is one script, and it saves the most common Docker debugging session there is.
# python3 port-check.py
# Try to bind the ports the app needs. A failure means something is already there.
import socket
for port in (3000, 5432, 6379):
s = socket.socket()
try:
s.bind(("127.0.0.1", port))
print(port, "- free")
except OSError:
print(port, "- TAKEN, find what is using it before you start the container")
finally:
s.close()
Expected: free ports print free, taken ports print taken. If 3000 is taken, I check what is listening there before I start anything, instead of reading a container error that only says the port is in use.
An API could not find its database, and the error said connection refused. The team rebuilt the API image twice, then restarted the database, then blamed the database password. The database was fine. The API and the database were on different networks, so the name db did not resolve, and the API failed on every request. The rebuilds changed nothing, because the code was never the problem.
Two things. First, the network is the first thing I check when a name does not resolve, before any rebuild. Second, every run command and every compose file names its network, and a container with no network flag is treated as broken in review. Try it now: pick any two containers you own and run docker inspect on each. If they are on different networks and they talk to each other, that is the first gap to close.
Wire a working two-container app: a web container and a database container on one custom network, talking by name, with only the web port published. It passes when the web reaches the database by name, the database has no published port, and a container on a different network cannot reach the database by name.
Success looks like this: nslookup prints the database IP. The web answers on localhost:3000. The database has no published port. The ping fails from bridge and answers from app-net. If the ping answers from bridge, the containers share a network you did not mean to share.
If nslookup fails, the container is not on the network you think it is. Run docker inspect and read the Networks block. If the port is already in use, change the host port, not the container port. If the database shows a published port, remove the -p flag. The database needs no door to the host.