How does ip netns exec
command create a mount namespace and prevent the changes from being propagated to other mount namespaces?
Following is the from the man page of ip-netns
:
For applications that are aware of network namespaces, the convention is to look for global network configuration files first in /etc/netns/NAME/ then in /etc/. For example, if you want a different version of /etc/resolv.conf for a network namespace used to isolate your vpn you would name it /etc/netns/myvpn/resolv.conf.
ip netns exec automates handling of this configuration, file convention for network namespace unaware applications, by creating a mount namespace and bind mounting all of the per network namespace configure files into their traditional location in /etc.
But, how does it manage the bind mount being visible only in that particular namespace?
Let me show an example. In one terminal, I create a network namespace ns3, and create a specific resolv.conf for ns3.
# ip netns add ns3 # mkdir /etc/netns/ns3 # echo "ns3 conf" > /etc/netns/ns3/resolv.conf # ip netns exec ns3 sleep 36000
Now in another terminal, I examine the /etc/resolv.conf.
# cat /etc/resolv.conf default conf
The change made by the bind mount is not reflected here.
The change is visible, only if i enter the mount namespace created by the ip netns
command.
# lsns | grep mnt 4026533472 mnt 1 13016 root sleep 36000 # nsenter -m -t 13016 # cat /etc/resolv.conf ns3 conf
So all works as expected.
Now let me try to do this directly with unshare
command, instead of using ip netns exec
.
I create a namespace again. With unshare
, I am creating a mount namespace and doing the bind mount inside that mount namespace. I assume this is what ip netns exec
command internally does.
# ip netns add ns4 # mkdir /etc/netns/ns4 # echo "ns4 conf" > /etc/netns/ns4/resolv.conf # unshare -m --propagation unchanged /bin/bash # mount --bind /etc/netns/ns4/resolv.conf /etc/resolv.conf
But this time when I check from another terminal, the changes have been propagated back which is not desired.
# cat /etc/resolv.conf ns4 conf
So what is the additional step that ip netns exec
does which prevent this propagation of changes? I assume it is related to the usage make-shared
or make-slave
flags, but couldn’t figure out exactly.
Advertisement
Answer
Found out that if I use # unshare -m --propagation slave /bin/bash
, the propagation is prevented.
ip netns exec
command seems to be running mount --make-rslave /
after unshare(CLONE_NEWNS)
is done.
i.e, after new mount namespace is created, / is mounted as slave in that namespace.