Course contentsShow
← Linux
Lesson 1459 of 1,81913. Containerization Primitives and NamespacesFree lesson

Network Namespaces and Virtual Networking

Construct isolated network stacks using veth pairs and bridges for container communication.

In this lesson, you will learn how to build isolated network environments by linking virtual Ethernet pairs to a Linux bridge, effectively mimicking how container runtimes provide networking to isolated processes.

The Foundation of Isolation

A Network Namespace (netns) provides a complete, private copy of the networking stack, including its own routing tables, firewall rules, and network interfaces. By default, a process inside a new namespace has no connectivity—not even a loopback device. To give it life, we use a veth pair. Think of a veth pair as a virtual patch cable: anything sent into one end pops out the other.

Wiring the Topology

To allow multiple namespaces to communicate or reach the external network, we bridge them together. A Linux bridge acts as a virtual Layer 2 switch. Here is how you construct this architecture:

  1. Create the Bridge: Set up a bridge device in the host’s default namespace to act as your internal hub.

    ip link add name br0 type bridge
    ip link set br0 up
    
  2. Create the Namespace: Establish the isolated environment.

    ip netns add container1
    
  3. Deploy the veth Pair: Create the pipe, placing one end in the host and the other inside the namespace.

    ip link add veth-host type veth peer name veth-ns
    ip link set veth-ns netns container1
    
  4. Connect and Configure: Attach the host-side end to the bridge and assign an IP address to the namespace-side end.

    ip link set veth-host master br0
    ip link set veth-host up
    ip netns exec container1 ip addr add 10.0.0.2/24 dev veth-ns
    ip netns exec container1 ip link set veth-ns up
    

By assigning unique IP addresses to the veth-ns interfaces in different namespaces and connecting them all to the same br0 bridge, you create a private virtual local area network. Packets travel from the namespace, through the veth "cable," into the bridge, and are then switched to the destination namespace or the host gateway. This is the fundamental mechanism that allows containers to talk to one another while remaining cryptographically and logically isolated from the host's primary network interfaces.

Key Takeaway: Network namespaces provide isolated stacks, while veth pairs and bridges function as the virtual wires and switches that interconnect those isolated environments.