Topic 6.2
How Containers Get a Network: Namespaces, veth & Bridges
In one line
A container's network is a Linux network namespace connected to the host through a veth pair plugged into a bridge, with NAT for outbound traffic and DNAT for published ports.
Think of it like this
Each container is a flat in a building with its own private phone line (a network namespace). A cable (veth pair) runs from each flat to the building's internal switchboard (the bridge), and the switchboard connects to the outside world through the building's main line (NAT on the host).
Key ideas
- 01
A NETWORK NAMESPACE is an isolated copy of the network stack: its own interfaces, IP addresses, routing table, and firewall rules. This is why a container has its own
localhost(Topic 1.3). - 02
A VETH PAIR is a virtual cable: whatever goes in one end comes out the other. One end is
eth0inside the container; the other sits on the host, attached to thedocker0BRIDGE (Topic 4.1), which acts as a switch for all containers on that host. - 03
Outbound traffic from containers is SNATed (masqueraded) to the host's IP; published ports (
-p 8080:80) are DNAT rules to the container's IP (Topic 4.3). User-defined networks add the embedded DNS server for name-based discovery (Topic 3.4; Docker course, Topic 4.3). - 04
The same building blocks power Kubernetes: every pod gets its own namespace and veth pair, and the CNI plugin decides how those connect across nodes (Topic 6.3).
Code & diagrams
Recreate what Docker does, by hand, on a Linux machine you control.
sudo ip netns add demo # a new network namespace
sudo ip link add veth-host type veth peer name veth-demo
sudo ip link set veth-demo netns demo # move one end into the namespace
sudo ip addr add 10.99.0.1/24 dev veth-host && sudo ip link set veth-host up
sudo ip netns exec demo ip addr add 10.99.0.2/24 dev veth-demo
sudo ip netns exec demo ip link set veth-demo up
sudo ip netns exec demo ip link set lo up
sudo ip netns exec demo ping -c 2 10.99.0.1 # the namespace can reach the host
sudo ip netns del demo # clean upExplain it without notes
Two containers on the same Docker bridge can talk to each other directly. Which component forwards their traffic?
Practice
Inside a container, run ip addr and ip route. What is the default gateway, and what is it on the host?
Trade-offs
- ↔
Bridged, NATed container networking is simple and isolated on one host, but NAT hides container IPs and adds overhead; multi-host platforms need a CNI that gives every pod a routable address.
Done when you can
I can explain network namespaces, veth pairs, and bridges.
I can create a namespace and connect it by hand.
I understand where NAT and DNAT happen for containers.