Networking: namespaces and isolated stacks
Docker does not invent isolation. It asks the Linux kernel for a fresh network namespace for every container.
key idea / Docker itselfcontainer / good pathhost / watch outproblem / blockedneutral
What a container really is
A container is an ordinary process wrapped in namespaces.
A private network stack per container
Why localhost differs
Sealed rooms need a door
Try it yourself
Alpine does not include ip until you add it. On Docker Desktop, docker0 lives in the Linux VM, so compare addresses with docker exec, not with the Mac’s ifconfig.
-
Step 1 · Start a container and install the tool
$ docker run -d --name box --rm alpine:3.20 sleep 300 $ docker exec box apk add --no-cache iproute2 -
Step 2 · The container’s interfaces
lois loopback.eth0is this container’s address, usually on172.17.0.0/16.$ docker exec box ip addr 1: lo: inet 127.0.0.1/8 2: eth0@if12: inet 172.17.0.2/16 -
Step 3 · Its route is not the host’s route
$ docker exec box ip route default via 172.17.0.1 dev eth0 172.17.0.0/16 dev eth0 scope link -
Step 4 · A second container has a different eth0
$ docker run -d --name box2 --rm alpine:3.20 sleep 300 $ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' box2 172.17.0.3 $ docker stop box box2
Recap
- A network namespace is a full, private copy of the network stack: devices, routes, firewall, ports.
- Each container gets its own namespace, so two containers can both listen on port 80.
localhostis private to the namespace you are in.- To leave the namespace a container needs a virtual cable to the host.
Quick check
Two containers both run nginx on port 80 on the same host. Why is there no port conflict?
Show answer
Each container has its own network namespace and therefore its own port table. The conflict would appear only if both were published on the same host port, or if both ran with --network host.