Network Namespace without Docker
Jul 6, 2016
Never miss our publications about Open Source, big data and distributed systems, low frequency of one email every two months.
Let’s imagine the following use case:
- I am connected to several networks (wlan0, eth0, usb0).
- I want to choose which network I’m gonna use when I launch apps.
- My app doesn’t allow me to choose a specific interface, it’s delegated to the OS that chooses the default one.
I could of course use Docker, which isolates networks, however Docker also isolates a lot of other things, needs images and is not really fit to launch existing apps on your computer.
We are going to use the same mechanism, network namespacing, but manually.
Let’s start by creating a network namespace named 4g:
sudo ip netns add 4g
Now we link an existing interface to it (we can use a virtual interface for complex setup but we’ll showcase it with the command line here).
Mine is named enp0s20u2:
sudo ip link set dev enp0s20u2 netns 4g
Once it’s done, the interface is not visible from the default namespace, let’s check it with:
ip addr show
Now that I hava configured the interface, I need to bind it to my 4g namespace. Either prefixing each of your commands or open a shell:
sudo ip netns exec 4g ip link set enp0s20u2 up
sudo ip netns exec 4g ip addr add 192.168.42.30/24 broadcast 192.168.42.255 dev enp0s20u2
sudo ip netns exec 4g ip route add default via 192.168.42.129
or
sudo ip netns exec 4g bash
> ip link set enp0s20u2 up
> ip addr add 192.168.42.30/24 broadcast 192.168.42.255 dev enp0s20u2
> ip route add default via 192.168.42.129
> exit
From now on it’s working but we don’t have a DNS.
DNS are usually set in /etc/resolv.conf
and the namespace functionality offers a mapping system (default) /etc/netns/
So let’s edit the file:
sudo mkdir -p /etc/netstat/4g
sudo echo "nameserver 8.8.8.8" > /etc/netstat/4g/resolv.conf
Now the namespace is fully functional. We can launch firefox for example:
sudo ip netns exec 4g firefox
Firefox is launched as root, which is not great. To fix it, use sudo:
USER=`whoami` sudo ip netns exec 4g sudo -u ${USER} firefox
Voila!