You don’t get to explicitly use Linux namespaces very often; one usually gets to make use of them when setting up containers or some sort of smart web hosting platform that allows hard resource limits to be put in place for customers, but even then the actual setup is hidden somewhere in the back. There are scenarios when containers simply require too much work for the particular task; I, at one time, faced the need of ensuring some network communication between 2 instances of the same service.
Communication? Same service? Have them listen on different addresses or on different ports and you’re done, you might say – but it’s not always that simple. If you have no control over the code but just want to replicate a certain behavior, there may simply not be an option to have instances listen on different ports. If the protocol also involves broadcasting, things become really complicated, as you don’t always have 2 IP addresses, on different interfaces, connected to the same network. Such scenario is easy to solve with virtualization or containers, but for this particular problem they’re overkill. The lightweight solution comes from manipulating Linux network namespaces.
Note: all commands below are to be normally run as root.
You need to have 2 tabs or consoles open. One of them will be the “master”, the second will be the “slave”; please make a mental note which is which. In the “slave” the following must be run:
# unshare -n /bin/bash # echo $$ xxxxxx
Please make note of the pid returned, this is required for the next step.
2. Set Network Up:
In the “master” window, the following must be run (please use the pid from the previous step):
# ip link add name veth0 type veth peer name veth1 netns xxxxxx # ip address add 192.168.10.10/24 dev veth0 # ip link set veth0 up
In the “slave”, the address also needs setting:
# ip address add 192.168.10.15/24 dev veth1 # ip link set veth1 up # ping 192.168.10.10 ...
3. Set Services Up:
I’m not going into this detail, as the communication path was all we were after. Anyway, looks easy? It is. Hope it helped!