Containers work on the principle of isolating one process running in the container from the process running on hosts or any other container. Let us see how containers isolate processes using Linux namespaces?
This is what provide containers to have a fresh runtime for any application irrespective of what other process are running on that hosts. It is a very useful feature as it seems like you are shipping the whole machine to be run instead of a piece of code.
When you feel like you are shipping a machine with your machine it makes sure you have confidence in your machine that it will not be affected by any other code running where you deploy your containers.
How containers actually implement that?
Isolation is nothing new it actually is present for a long time but in the current version of our Linux machines, it is generally implemented using Linux namespaces.
Linux namespaces are the concept that makes sure you can isolate particular resources from others. This includes resources like network, process, filesystem, etc. Linux provides a command interface to implement it using unsure command. There are 7 namespaces that you can interact with
- Mount – filesystem mount points
- UTS – Domain Name
- IPC – isolate interprocess communication (IPC) resources
- PID – isolate the PID number space
- Network – isolate network interfaces
- User – isolate UID/GID number spaces
- Cgroup – isolate cgroup root directory
Let’s see some examples.
Opening a terminal in different namespaces.
sudo unshare -u /bin/sh
This will open a terminal in different namespaces and whatever you do in that will not affect the main system. Try changing hostname by using below command
hostname new_hostname
#this hostname will be visible in your new terminal but outside it will be the older hostname.
You can read more about Linux namespaces and how to use them here.
http://man7.org/linux/man-pages/man1/unshare.1.html
How a container is actually created.
It is created by a combination of the below commands.
chroot:
Change the root filesystem of the process to the one that you specified.
unshare:
Isolate the spaces for your process and filesystem.
cgroups:
Apply the restriction that your process can use in terms of memory, network, CPU etc.
Follow this link for a complete overview of containers from scratch.
This was very basic of how containers implement its functionalities.
If you like the article join our Facebook group:https://www.facebook.com/groups/327836414579633/ and Linkedin group:https://www.linkedin.com/groups/10441297/