Photo by Łukasz Bacik on Unsplash

The Magic of the Linux Namespaces — a short exercise

TL;DR version:

Below you can find the explanation of the above exercise :)

Terminal 1

Start a container

$ docker run -ti debian

Now, two short tests — check the IP address assigned to the container and create a “foo-bar” file in its root filesystem (first checking that it doesn’t exist already):

root@e339cd7b46d8:/# ip a show dev eth0 | grep inet
inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
root@e339cd7b46d8:/# ls /
bin ...
root@e339cd7b46d8:/# touch /foo-bar
root@e339cd7b46d8:/# ls /
bin ... foo-bar ...

Finally, let’s start the process that later we are going to use to identify that particular container (or rather the namespaces used by it — in terminal 2).

root@e339cd7b46d8:/# sleep 1000

Terminal 2

Start privileged container:

$ docker run -ti --privileged --pid=host debian

Check that (as for the time being) It differs from the former one (has different IP address, and there is no “foo-bar” file in its root filesystem):

root@1172a97ce924:/# ip a s dev eth0 | grep inet
inet 172.17.0.4/16 brd 172.17.255.255 scope global eth0
root@1172a97ce924:/# ls /
bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var

The privileged here means that inside of that container we are using the host’s pid namespace (thus the --pid=host option). And thow we can “see” all the host’s processes, not only the processes of that particular container. For instance, we cat see the sleep 1000 process from the former container:

root@1172a97ce924:/# ps ax | grep sleep
2503 pts/0 S+ 0:00 sleep 1000

And NOW — the magic — let’s say:

root@1172a97ce924:/# nsenter -a -t 2503 bash
root@e339cd7b46d8:/#

Please notice that the prompt (its hostname part exactly, in the second line) has changed!

Let’s check the IP and the root filesystem:

root@e339cd7b46d8:/# ip a s dev eth0 | grep inet
inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
root@e339cd7b46d8:/# ls /
bin ... foo-bar ...

Yep, we … moved (?) to the container that we have run in terminal 1! Please do some experiments with ps etc. Type exit to move back to the privileged one!

Summary

It is only a short example I have tested recently during my experiments — more about Linux Namespaces you can find (for instance ;)) in the series of articles I have devoted them — link below!

Thanks for reading!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store