DEV Community

Cover image for Your Container Is Not a VM: Practical Linux Namespaces with unshare
Lyra
Lyra

Posted on

Your Container Is Not a VM: Practical Linux Namespaces with unshare

A container is not a small virtual machine. There is no guest kernel, no emulated hardware, and usually no boot process. A container is an ordinary Linux process that has been given a different view of the system: its own process IDs, its own network stack, its own mount table, its own hostname. The kernel object that provides each of those views is a namespace.

That distinction matters when something breaks. If you treat a container like a VM, you look for the wrong things. You check "the container's IP" instead of the veth pair. You wonder why PID 1 will not die. You try to mount something and get EPERM because the process has CAP_SYS_ADMIN only inside a user namespace, not on the host.

This article builds namespaces by hand with unshare, so you can see exactly what a container runtime is assembling.

The eight namespaces

Linux currently exposes eight namespace types. Each one wraps a different global resource:

Namespace Flag What it isolates
Cgroup CLONE_NEWCGROUP The visible cgroup root
IPC CLONE_NEWIPC System V IPC and POSIX message queues
Network CLONE_NEWNET Devices, stacks, routes, firewall rules, ports
Mount CLONE_NEWNS Mount points
PID CLONE_NEWPID Process ID numbers
Time CLONE_NEWTIME CLOCK_MONOTONIC and CLOCK_BOOTTIME offsets
User CLONE_NEWUSER UIDs, GIDs, and capabilities
UTS CLONE_NEWUTS Hostname and NIS domain name

The kernel documentation is blunt about the purpose: "One use of namespaces is to implement containers." That is the whole trick. Everything else in a container stack — images, layered filesystems, cgroups, seccomp, LSMs — is either packaging or additional isolation around these eight objects.

Creating most namespaces requires CAP_SYS_ADMIN. User namespaces are the exception: since Linux 3.8, an unprivileged process can create one. That is why rootless containers are possible at all. When you pass CLONE_NEWUSER together with other namespace flags, the kernel creates the user namespace first, so the new process has the capabilities needed to create the remaining namespaces.

See the namespace handles

Every process has a /proc/PID/ns/ directory. The entries are symbolic links whose targets include a namespace type and an inode number:

$ ls -l /proc/$$/ns
lrwxrwxrwx. cgroup -> cgroup:[4026531835]
lrwxrwxrwx. ipc    -> ipc:[4026531839]
lrwxrwxrwx. mnt    -> mnt:[4026531840]
lrwxrwxrwx. net    -> net:[4026531969]
lrwxrwxrwx. pid    -> pid:[4026531836]
lrwxrwxrwx. user   -> user:[4026531837]
lrwxrwxrwx. uts    -> uts:[4026531838]
Enter fullscreen mode Exit fullscreen mode

Two processes are in the same namespace if the device and inode numbers of the corresponding links match. The text after the colon is the inode number, so this is usually enough:

$ readlink /proc/$$/ns/net
net:[4026531992]
$ sudo readlink /proc/1/ns/net
net:[4026531992]
Enter fullscreen mode Exit fullscreen mode

Same number, same network namespace. A container runtime does not need a special API to answer "is this process in the host network namespace?" It can compare inode numbers.

A PID namespace in one line

The smallest useful demonstration is also the most surprising:

$ unshare --fork --pid --mount-proc readlink /proc/self
1
Enter fullscreen mode Exit fullscreen mode

The shell you ran it from still has its normal PID. The child process is PID 1 inside the new PID namespace, and /proc was remounted so that /proc/self reflects that namespace. Without --mount-proc, the old /proc would still show host PIDs, which is confusing but not wrong: /proc shows the processes visible to the PID namespace of whoever mounted it.

Two details are easy to miss:

  • A PID namespace applies to newly created processes. unshare --pid without --fork does not move the program you exec into the new namespace, because exec does not create a process. That is why the example uses --fork.
  • The first process in a PID namespace is PID 1, and it has init-like semantics. If it exits, the kernel sends SIGKILL to every other process in that namespace. A process in an ancestor namespace can send SIGKILL or SIGSTOP to it, but other signals are delivered only if PID 1 has installed a handler.

This is why "just run a shell as PID 1" is a bad container entrypoint. A shell does not reap orphaned children or forward signals the way an init process should.

A rootless user namespace

User namespaces change the identity map. You can be UID 1000 on the host and UID 0 inside:

$ id -u
1000
$ unshare --user --map-root-user sh -c 'id; cat /proc/self/uid_map'
uid=0(root) gid=0(root) groups=0(root)
         0       1000          1
Enter fullscreen mode Exit fullscreen mode

The mapping is one line: inside UID 0 maps to outside UID 1000, with a range of one. The process has a full set of capabilities in the new user namespace, but no capabilities in the parent namespace. That is the key sentence. Root inside is not root outside.

This is also why file ownership gets strange. If a file on the host is owned by UID 1000 and your namespace maps only UID 1000 to 0, the file appears as root inside. A file owned by UID 1001 is not mapped at all and shows up as the overflow UID, usually 65534 (nobody). The kernel does not pretend the ID exists.

You can combine the user namespace with mount, UTS, and PID namespaces:

$ unshare --user --map-root-user --mount --uts --pid --fork --mount-proc bash
# id
uid=0(root) gid=0(root) groups=0(root)
# hostname mini-container
# mount -t tmpfs tmpfs /tmp
# findmnt /tmp
TARGET SOURCE FSTYPE
/tmp   tmpfs  tmpfs
Enter fullscreen mode Exit fullscreen mode

Inside this shell you can set a hostname, mount a tmpfs over /tmp, and see a PID namespace where your shell is PID 1. Outside, the host hostname, mounts, and process table are unchanged. On distributions that restrict unprivileged user namespaces, the first command will fail with EPERM; that is a policy choice, not a bug in the commands.

The mount namespace has one more subtlety: mount propagation. A new mount namespace created by unshare is set to private propagation by default (since util-linux 2.27), so mounts do not leak back to the host. If you explicitly request shared propagation, a mount can propagate. You can inspect the flags with:

findmnt -o TARGET,PROPAGATION /
Enter fullscreen mode Exit fullscreen mode

A network namespace with a veth pair

A fresh network namespace starts with a loopback interface that is down and no route to anything. To make it useful, connect it to the host with a veth pair. A veth pair is two virtual Ethernet devices; a packet sent on one is immediately received on the other, and the link state of the pair is down if either end is down.

This is a complete disposable lab:

# Create a named network namespace
sudo ip netns add demo

# Create a veth pair, one end in the host namespace, one in demo
sudo ip link add veth-host type veth peer name veth-demo
sudo ip link set veth-demo netns demo

# Host side: 10.200.0.1/24
sudo ip addr add 10.200.0.1/24 dev veth-host
sudo ip link set veth-host up

# Namespace side: 10.200.0.2/24, plus loopback
sudo ip netns exec demo ip addr add 10.200.0.2/24 dev veth-demo
sudo ip netns exec demo ip link set veth-demo up
sudo ip netns exec demo ip link set lo up

# Test it
sudo ip netns exec demo ping -c 2 10.200.0.1
Enter fullscreen mode Exit fullscreen mode

Clean up with:

sudo ip netns pids demo | xargs -r sudo kill
sudo ip netns delete demo
Enter fullscreen mode Exit fullscreen mode

Deleting the namespace destroys the veth device inside it, and the host-side peer goes with it. If you moved a physical interface into the namespace instead, the kernel would move it back to the initial namespace when the namespace is freed.

A named network namespace is just a file under /var/run/netns/. ip netns exec also creates a mount namespace and bind-mounts per-namespace configuration files, which is why tools that are not namespace-aware can still read the right /etc/resolv.conf. That is a convenience layer, not part of the network namespace itself.

Entering a namespace

unshare creates namespaces. nsenter enters existing ones. Given a target PID:

sudo nsenter --target 1234 --mount --uts --ipc --net --pid
Enter fullscreen mode Exit fullscreen mode

nsenter forks by default when entering a PID namespace so that the new program and its children share the same PID namespace. You can also enter all namespaces at once with --all, or enter by an explicit namespace file such as /proc/1234/ns/net.

This is the same operation a runtime uses for docker exec or podman exec: find the target process, open its namespace files, setns() into them, then execute the command. The difference is that the runtime already knows which namespaces belong to the container.

To list namespaces on a host, lsns is the quick view:

lsns -t net
lsns -t pid
Enter fullscreen mode Exit fullscreen mode

What namespaces do not do

Namespaces isolate visibility, not resource usage and not every privilege. A process can be in its own network namespace and still burn every CPU cycle on the host. It can have its own mount namespace and still write to a host directory that was bind-mounted into it. It can have a user namespace and still be vulnerable to a kernel bug.

A real container also needs:

  • cgroups to bound CPU, memory, I/O, and process counts;
  • capability dropping so the process does not keep privileges it does not need;
  • seccomp to reduce the syscall surface;
  • LSMs such as AppArmor or SELinux for path and operation policy;
  • a root filesystem, usually assembled from image layers and pivoted into place.

The namespaces are the part that makes the process feel like it is alone. The rest is the part that keeps it from hurting the host.

The mental model to keep

When you debug a container, ask which namespace you are actually looking at:

  • ps shows PIDs in your current PID namespace, not necessarily the host's.
  • ip addr shows interfaces in your current network namespace; the host may see a veth peer instead.
  • mount shows your current mount namespace; a bind mount may exist in one and not the other.
  • hostname shows the UTS namespace, which is why a container can have a name that does not exist in DNS.
  • id shows UIDs mapped into your user namespace; UID 0 inside may be UID 1000 outside.

Once that clicks, containers stop being magic and start being a composition of kernel features you can inspect, reproduce, and debug with tools that are already on the box.

References

Top comments (0)