Isolate containers with a user namespace.

Linux namespaces provide isolation for running processes, limiting their access to system resources without the running process being aware of the limitations.

alixan
2 min readApr 24, 2022

For containers whose processes must run as the root user within the container, you can re-map this user to a less-privileged user on the Docker host. The mapped user is assigned a range of UIDs which function within the namespace as normal UIDs from 0 to 65536, but have no privileges on the host machine itself.

Let’s start by examining the ownership of a container’s process by running up a simple container based on the Alpine Linux distribution.

docker container run -it — name foo alpine sh
PID USER TIME COMMAND
1 root 0:00 sh
10 root 0:00 ps

If we perform a process listing, we can see that the shell process, which has a process ID of one is running as the root user.it’s normal

then if we use the Docker container top command to list the container’s process

docker container top foo -eo user,pid,comm

top : Display the running processes of a container

USER PID COMMAND
root 4844 sh

shell process is running in a container, its owner, root, is the same in and outside the container. The container and its process have their own file system, but if the process were able to break out of this contained environment, it would have access to file system objects owned by the root user.Remove the running container

docker container rm -f foo

f : force

vim /etc/docker/daemon.json     { 
“userns-remap”: “default”
}

We need to recycle the daemon for the change to take effect, which we do using the systemctl restart command

systemctl restart docker.servicecat /etc/subuid
alixan:100000:65536
dockremap:165536:65536

Let’s run container and see what effect the configuration change has. if we run an alpine container

docker container run -it — name foo alpine sh

We already have the Alpine image in the local cache, but Docker downloads the image from the Docker hub as if it weren’t there. This is because the images used by the dockremap user’s subordinate user ID needs to be owned by that subordinate user ID. The original Alpine image in a cache was owned by the root user. Inside the container, our user is still the root user, no change there. But if we detach from the container again, and check the process from the host’s perspective, instead of running as the root user, this type is running as the user with UID 165536.

docker container top foo -eo user,pid,commUSER PID COMMAND
165536 6856 sh

if we take a look at your path in /var/lib/docker

ls -l /var/lib/docker/
drwx--x--- 13 root 165536 4096 Apr 24 07:57 165536.165536

References:

man7.org

--

--