Linux 101 : Namespace and Bind mounts - unshare, mount --bind, ... -
An empty namespace is deleted by the system. In order to keep a namespace open, a process needs to be running inside it or it needs to have a bind mount.
Bind mounts are used to mount a directory onto another directory so that they both point to the same content.
The below command "bindmounts" binds the "/proc/$$/ns" directory to another location in the filesystem "/var/run/netns/net1". for example:
The "$$" sign means the current shell process ID.
To be able to run in an existing namespace a process could use the "setns" command.
The network namespace of a host is different from a newly created namespace.
We could test that by running the below command on our host:
Then, we create a new network namespace using the "unshare" command, and we run the same command inside:
And since there is no process inside the namespace, when the above command exits, it gets removed.
We open a shell inside a new network namespace using the below:
Then we run the following:
we get the same output as before as our previous namespace.
We check the identifiers of the namespaces of the current shell symbolized by the "$$" sign:
Then, we make the namespace persist by creating a bind mount as follows:
The below command lists all the available network namespaces:
And the following command tells us in which network namespace our shell is running:
Since we have created the bind mount, our namespace will persist once we exit it.
We can check that using the below:
Because we exited, our shell is no longer running in that namespace - but the namespace is still there because of the bind mount -. We could verify that by running the following command:
If we want to double-check if our created namespace is still around, we could run the following in it: