Last Updated: February 25, 2016
·
7.287K
· bt3gl

Quick ip-netns

ipsuite of tools that was supposed to deprecate ifconfig, route, etc. seven years ago.

ip-netns allows us to set up isolated, private virtual subnets on one host, and connect them to each other with virtual ethernet devices, to simulate a larger LAN on a single host.

For example: Docker uses ip-netns in their implementation (LXC to build Docker).

Creating Namespaces

Creating two virtual ethernet devices that are paired together, one inside the NAME and other in the root namespace:

$ sudo ip netns add NAME
$ sudo ip link add veth0 type veth peer name veth1

Now we put veth1 into NAME:

$ sudo ip link set veth1 netsn NAME

Doing ip addr directly on the command line, you see veth0, but veth1 disappeared.

COMMAND will be executed inside of the new network namespace:

$ ip netns exec <NAMESPACE><COMMAND> 

This shows the network status inside the namespace:

$ sudo ip netns exec NAME ip addr

Next we can add IP addresses using ip addr both inside and outside the namespace, and have three: veth0, veth1, and lo. Choosing /31 so we only consume two IPs:

$ sudo ip addr add 10.1.1.0/31 dev veth0
$ sudo ip netns exec NAME ip addr add 10.1.1.1/31 dev veth1
$ sudo ip link set veth0 up
$ sudo ip netns exec NAME ip link set veth0 up
$ sudo ip netns exec NAME ip link set lo up

Setting a route for traffic inside the namespace to reach the outer world:

$ sudo ip netns exec NAME ip route add default via 10.1.1.0

Sometimes we need a rule to tell iptables to add the source 10.1.1.0/31 to the NAT table, to intercept any traffic headed to 0.0.0.0/0 (any destination) and to masquerade that traffic. In this case, use NAT so that to the outside world traffic appears to be from the same IP address as the root namespace:

$ sudo iptables -t nat -A POSTROUTING -s 10.1.1.0/31 -d 0.0.0.0/0 -j MASQUERADE

Allowing NAT:

$ sudo sysctl net.ipv4.ip_forward=1

Testing:

$  sudo ip netns exec NAME ping google.com

Traffic Control

You can create namespaces to degrade the connection from one service to another using tc tool, and to verify how the services behave when the network is misbehaving.

For instance, we can tell the kernel to drop 30% of the packets that are sent through veth1 to simulate a “bad network”. Then we use ping to see the new packet queuing strategy in action:

$ sudo ip netns exec blue tc qdisc add dev veth1 root netem loss 30%
$ ping 10.1.1.1

1 Response
Add your response

how did you use tc qdisc inside a namespace? For me it always says RTNETLINK answers: Invalid argument.

According to this source https://lists.linux-foundation.org/pipermail/containers/2009-September/020473.html qdisc is not supported inside a namespace.

over 1 year ago ·