Linux Network Namespaces

From Leo's Notes
Last edited on 1 September 2019, at 06:20.

Linux network namespaces is a software implementation of Virtual Routing and Forwarding (VRFs) in built in the linux kernel. Similar to how VLANs segregate level 2 traffic on a single networking device, VRF allows level 3 traffic to be segregated on one device. This may be useful when traffic needs to be separated on different networks for security or when multiple routers in a software defined network need to be created.

If your linux kernel does not have network namespaces enabled, the following command will return an error:

$ ip netns
Object "netns" is unknown, try "ip help".

Overview[edit | edit source]

The following table lists all the common tasks when working with network namespaces.

Action Command
Create a new namespace ip netns add $namespaceName
List all namespaces ip netns list or simply: ip netns
Delete a namespace ip netns delete $namespaceName
Executing a command in a namespace ip netns exec $namespaceName $command

After creating a network namespace, you will need to add interfaces to the namespace.

Working with Namespaces[edit | edit source]

You can start services or programs under a specific namespace using the ip netns exec command. If you wish to work in a specific namespace, you can start a shell in the namespace to avoid needing to prefix every command with the ip netns exec command.

Example:

# Instead of running commands in a namespace explicitly:
$ ip netns exec qrouter-97db7930-3223-4452-add8-6b971459a3b1 ip a
$ ip netns exec qrouter-97db7930-3223-4452-add8-6b971459a3b1 route -n

# You could start a shell in the namespace and work from there:
$ ip netns exec qrouter-97db7930-3223-4452-add8-6b971459a3b1 bash
# Now inside the qrouter-97db7930-3223-4452-add8-6b971459a3b1 namespace
$ ip a
$ route -n

Adding Interfaces[edit | edit source]

Local Loopback Interface[edit | edit source]

# Enable the loopback device
ip netns exec $namespace ip link set dev lo up

Virtual interfaces[edit | edit source]

You cannot add network interfaces directly to a namespace. You can only add virtual interfaces and have that bridge with your physical interfaces.

$ ip link add $vethA type veth peer name $vethB
$ ip link
18: vethA: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN mode DEFAULT 
    link/ether fa:16:3e:c8:09:52 brd ff:ff:ff:ff:ff:ff
22: vethB: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN mode DEFAULT 
    link/ether fa:16:3e:d2:14:e3 brd ff:ff:ff:ff:ff:ff
$ ip link set $vethA netns $namespace

At this point, $vethA should be visible in $namespace