Understanding Single-Host Container Networking with Linux Namespaces, veth, Bridges, and iptables
This tutorial explains how to isolate, virtualize, and connect Linux network stacks on a single host using network namespaces, virtual Ethernet pairs, Linux bridges, routing, NAT, and iptables, covering both basic concepts and practical commands for Docker and Podman environments.
Container networking can feel magical, but it is fundamentally built on Linux network namespaces, virtual Ethernet (veth) devices, and bridges. By creating isolated network namespaces, you can give each container its own network stack without needing separate images.
Key steps include:
Creating a network namespace with sudo ip netns add netns0 and entering it using sudo nsenter --net=/var/run/netns/netns0 bash .
Setting up a veth pair: sudo ip link add veth0 type veth peer name ceth0 , moving one end to the namespace ( sudo ip link set ceth0 netns netns0 ), and configuring IP addresses.
Connecting multiple containers via a Linux bridge: sudo ip link add br0 type bridge , sudo ip link set br0 up , and attaching veth interfaces to the bridge with sudo ip link set veth0 master br0 and sudo ip link set veth1 master br0 .
Adding routes and enabling IP forwarding ( echo 1 > /proc/sys/net/ipv4/ip_forward ) so containers can reach external networks.
Applying NAT using iptables: sudo iptables -t nat -A POSTROUTING -s 172.18.0.0/16 ! -o br0 -j MASQUERADE and exposing container ports with DNAT rules.
Testing connectivity with ping and curl from both the host and container namespaces.
The article also compares Docker network drivers (host, none, bridge) and discusses rootless containers using Podman and slirp4netns, highlighting limitations such as the need for root privileges to configure veth devices.
Overall, the guide demonstrates a practical, step‑by‑step approach to building a functional container network on a single Linux host, suitable for development, testing, and understanding the underlying mechanisms of container networking.
IT Architects Alliance
Discussion and exchange on system, internet, large‑scale distributed, high‑availability, and high‑performance architectures, as well as big data, machine learning, AI, and architecture adjustments with internet technologies. Includes real‑world large‑scale architecture case studies. Open to architects who have ideas and enjoy sharing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.