Khalil

A practical look at Linux network namespaces

Network namespaces are one of those things that look intimidating until you realise they are just a way of giving a process its own, completely separate set of network interfaces and routing tables.

Creating one

Everything you need is in iproute2. Start with a namespace and a pair of virtual cables connecting it to the host:

# ip netns add demo
# ip link add veth0 type veth peer name veth1
# ip link set veth1 netns demo

Giving it an address

Now bring both ends up and assign addresses. From the host's point of view the namespace is just another directly connected network:

# ip addr add 10.0.0.1/24 dev veth0
# ip link set veth0 up

# ip netns exec demo ip addr add 10.0.0.2/24 dev veth1
# ip netns exec demo ip link set veth1 up
# ip netns exec demo ip link set lo up

Ping across the pair and it just works:

# ip netns exec demo ping -c1 10.0.0.1

Getting to the outside world

By default the namespace has no route out. Enable forwarding and add a NAT rule:

# sysctl -w net.ipv4.ip_forward=1
# iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE
# ip netns exec demo ip route add default via 10.0.0.1

Why this is useful

Once you can script namespaces, you have a clean way to test routing, firewalls, and failover without touching the host's real networking. It is also exactly how most container runtimes isolate networking, so understanding it pays off when something goes wrong at 2am.

Tip: ip netns exec <ns> bash drops you into a shell inside the namespace. Add a PS1 prefix so you never forget where you are.

← Back to posts