Docker [E02]: PID namespaces
Table of Contents
So now we understood why it is important to make these lightweight isolated environments on Linux, we can ask how can we do that. If you remember from the previous post on docker, we mentioned some namespaces that will allow us to make these isolated environments. In this post, we will describe only one of them, which is PID namespace.
PID Namespaces:
To understand what this is we need to go one step back and try to describe how Linux processes work. Simply a Linux operating system is made up of one process, namely “init”, so once the OS runs this process is the only process that gets executed. This process is responsible for creating all the other processes that are needed for the OS to be used by other applications. Think of it as a tree where the root is the init process and all other processes are children of that process. The child processes themselves can have their own children.
# This shows the process tree on Ubuntu VM
pstree
What namespaces do exist on my machine?
# This command will show the namespaces that are applied to the current root process (init) and all its children
# unless there is a child that has another set of namespaces applied to it then the parent namespaces will not apply then
lsns
What pid namespace actually is?
It is a numbering for the existing processes which gives a process a PID, a unique number to identify this process. Following what we mentioned before, as init is the root of all processes, it is given an ID of one.
pstree -p
How to create a pid namespace?
# The unshare command forks a new process from the process that will run the below command
# This command will create a new pid namespace and run a command "bash" in it as the root of that new namespace
# So, the new bash process will think that it is the root of the process tree and not know
# the process that created it or any other process
unshare --pid --fork --mount-proc /bin/bash
Yes, the root process that is running the bash process with pid=1 and another child that was created from the parent bash to run the pstree command.
How does it look from outside of the new namespace?
pstree -p
As I am connecting to the testing maching using SSH, you can see that any command that I run is created as a child of that bash process that is conecting me to the SSH deamon. Also the process that we create with a new PID namespace is visible from the outside to the root and has a global PID, so it is still a part of the original tree.