This tutorial explores Linux network namespaces, focusing on container network isolation and commands for creating, managing, and connecting namespaces.
Use this file to discover all available pages before exploring further.
In this tutorial, we take a deep dive into Linux network namespaces—the building blocks of container network isolation (e.g., in Docker). Think of your host as a house and each network namespace as a private room: containers inside one room cannot see interfaces or processes in another. The host, however, has a global view of all “rooms.”
Most of these commands require root privileges or sudo. Ensure you have the appropriate permissions before proceeding.
Inside a container’s PID namespace, a process always appears as PID 1. From the host’s root namespace, the same process has a distinct PID among all host processes:
# Inside the container (PID namespace)ps aux# ...root 1 0.0 0.0 4528 828 ? Ss 03:06 0:00 nginx# On the hostps aux# ...root 3816 1.0 0.0 4528 828 ? Ss 06:06 0:00 nginx
To create a virtual “cable” between red and blue, use a veth pair:
# Create veth pairip link add veth-red type veth peer name veth-blue# Move each end into its namespaceip link set veth-red netns redip link set veth-blue netns blue# Assign IPs and bring up interfacesip -n red addr add 192.168.15.1/24 dev veth-redip -n red link set veth-red upip -n blue addr add 192.168.15.2/24 dev veth-blueip -n blue link set veth-blue up
Test connectivity:
ip -n red ping -c1 192.168.15.2# 64 bytes from 192.168.15.2: icmp_seq=1 ttl=64 time=0.xxx ms
ARP tables populate automatically:
ip -n red arpip -n blue arp# 192.168.15.1 ether 7a:9d:9b:c8:3b:7f C veth-blue
Connecting many namespaces via direct veth pairs is impractical. Instead, create a Linux bridge on the host:
# Create and enable bridgeip link add v-net-0 type bridgeip link set v-net-0 up
Remove the direct link in red:
ip -n red link del veth-red
Recreate veth pairs for each namespace and attach them to the bridge:
# red ↔ bridgeip link add veth-red type veth peer name veth-red-brip link set veth-red netns redip link set veth-red-br master v-net-0# blue ↔ bridgeip link add veth-blue type veth peer name veth-blue-brip link set veth-blue netns blueip link set veth-blue-br master v-net-0
Assign IPs and bring them up:
ip -n red addr add 192.168.15.1/24 dev veth-redip -n red link set veth-red upip -n blue addr add 192.168.15.2/24 dev veth-blueip -n blue link set veth-blue up
All namespaces on v-net-0 can now communicate via the bridge.
Be careful when modifying iptables rules on production systems. Always test in a safe environment first.
# Masquerade outbound traffic from your virtual subnetiptables -t nat -A POSTROUTING -s 192.168.15.0/24 -j MASQUERADE# Set default route in the namespaceip -n blue ip route add default via 192.168.15.5
Now blue can reach the internet (e.g., 8.8.8.8):
ip -n blue ping -c1 8.8.8.8# 64 bytes from 8.8.8.8: icmp_seq=1 ttl=115 time=XX ms