This tutorial explores Linux network namespaces, focusing on container network isolation and commands for creating, managing, and connecting namespaces.
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:
Copy
Ask AI
# 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:
Copy
Ask AI
# 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:
Copy
Ask AI
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:
Copy
Ask AI
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:
Copy
Ask AI
# Create and enable bridgeip link add v-net-0 type bridgeip link set v-net-0 up
Remove the direct link in red:
Copy
Ask AI
ip -n red link del veth-red
Recreate veth pairs for each namespace and attach them to the bridge:
Copy
Ask AI
# 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:
Copy
Ask AI
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.
Copy
Ask AI
# 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):
Copy
Ask AI
ip -n blue ping -c1 8.8.8.8# 64 bytes from 8.8.8.8: icmp_seq=1 ttl=115 time=XX ms