Network Namespace without Docker

Network Namespace without Docker

By Pierre SAUVAGE

Jul 6, 2016

Categories: Hack | Tags: DNS, Docker, Linux, Namespaces, Network, VLAN

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/<ns>/resolv.conf -> (<ns>) /etc/resolv.conf

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!

Canada - Morocco - France

International locations

10 rue de la Kasbah
2393 Rabbat
Canada

We are a team of Open Source enthusiasts doing consulting in Big Data, Cloud, DevOps, Data Engineering, Data Science…

We provide our customers with accurate insights on how to leverage technologies to convert their use cases to projects in production, how to reduce their costs and increase the time to market.

If you enjoy reading our publications and have an interest in what we do, contact us and we will be thrilled to cooperate with you.