Skip to content
systemcoding.dev
Systems Programming

What Linux Namespaces Are and Why Containers Use Them

Learn what Linux namespaces are, the eight kinds the kernel has, how to see them under /proc and how containers combine them to give a process its own view.

6 min read
Summarize in AI
Flat illustration of shipping containers stacked on a ship, with the Linux, QEMU and NixOS logos.

A container is not a kind of virtual machine and not a kernel feature with that name. It is an ordinary Linux process that has been given its own view of the system: its own list of processes, its own network interfaces, its own hostname, its own mounted filesystems. The kernel feature that gives the process that private view is the namespace. Once you know what a namespace is, container runtimes stop being magic, because most of what they do is call a handful of system calls in a particular order. This post explains the idea, lists the eight kinds on Linux 6.12, shows how to inspect them with ordinary commands and ends with the small piece of C that creates one.

The idea

A namespace wraps a global resource so that processes inside it see their own isolated instance of it. The resource is still one kernel structure, and processes in different namespaces get different answers to the same question. Ask the hostname inside one namespace and you get the name set there, even though another process on the same kernel sees a different name. Ask for the list of processes and you see only those in your process ID namespace, and the first of them has PID 1.

What a namespace does not do is limit use. It controls what a process can see and name, and not how much CPU, memory or disk it can consume. Limits are the job of control groups, which the next posts in this series cover. A container needs both: namespaces for isolation of view, cgroups for isolation of resources.

The eight kinds

Linux 6.12 has eight namespace types, each created with its own clone flag:

NamespaceFlagWhat it isolatesSince
MountCLONE_NEWNSThe tree of mounted filesystems2.4.19
UTSCLONE_NEWUTSHostname and NIS domain name2.6.19
IPCCLONE_NEWIPCSystem V IPC objects and POSIX message queues2.6.19
PIDCLONE_NEWPIDProcess IDs2.6.24
NetworkCLONE_NEWNETInterfaces, routing tables, firewall rules, ports2.6.24 (complete by 2.6.29)
UserCLONE_NEWUSERUser and group IDs and capabilities3.8
CgroupCLONE_NEWCGROUPThe view of the cgroup hierarchy4.6
TimeCLONE_NEWTIMEOffsets for the boot and monotonic clocks5.6

The mount namespace was the first, which is why its flag has the unspecific name CLONE_NEWNS: nobody expected there to be more. Each type isolates one thing, and a process can be in a different namespace of every type at once, so a container is a particular combination, not a single object.

Seeing your own namespaces

Every process has a directory /proc/<pid>/ns/ with one entry per namespace type. Each is a symbolic link whose target names the type and an inode number that identifies the namespace:

Shell
ls -l /proc/self/ns
Text
total 0
lrwxrwxrwx 1 alice alice 0 Nov 23 09:14 cgroup -> 'cgroup:[4026531835]'
lrwxrwxrwx 1 alice alice 0 Nov 23 09:14 ipc -> 'ipc:[4026531839]'
lrwxrwxrwx 1 alice alice 0 Nov 23 09:14 mnt -> 'mnt:[4026531841]'
lrwxrwxrwx 1 alice alice 0 Nov 23 09:14 net -> 'net:[4026531840]'
lrwxrwxrwx 1 alice alice 0 Nov 23 09:14 pid -> 'pid:[4026531836]'
lrwxrwxrwx 1 alice alice 0 Nov 23 09:14 pid_for_children -> 'pid:[4026531836]'
lrwxrwxrwx 1 alice alice 0 Nov 23 09:14 time -> 'time:[4026531834]'
lrwxrwxrwx 1 alice alice 0 Nov 23 09:14 time_for_children -> 'time:[4026531834]'
lrwxrwxrwx 1 alice alice 0 Nov 23 09:14 user -> 'user:[4026531837]'
lrwxrwxrwx 1 alice alice 0 Nov 23 09:14 uts -> 'uts:[4026531838]'

The inode numbers are example values and differ per boot. What matters is that two processes whose links show the same number share that namespace, and different numbers mean different namespaces. A process on a normal system shares all of them with init, the initial namespaces. The two _for_children entries are the namespaces a child process will be placed in, which differ from the current ones only after an unshare of that type.

The tool lsns lists every namespace on the system and how many processes are in each:

Shell
lsns -t uts
Text
        NS TYPE NPROCS   PID USER COMMAND
4026531838 uts     214     1 root /sbin/init
4026532611 uts       3  8841 root nginx: master process nginx -g daemon off;

On a host running one container, you see the initial UTS namespace with the whole system in it and a second one, created by the container runtime, holding the three processes of the container. The numbers are an example.

Compare two processes

You can check whether a container's process is in the host's network namespace without any special tool, by comparing the links. A process started with the host's network, as docker run --network host does, reports the same net: number as init:

Shell
readlink /proc/1/ns/net /proc/8841/ns/net
Text
net:[4026531840]
net:[4026532687]

The numbers differ, so process 8841 has its own network namespace. If the second line matched the first, the process would share the host's network and see its interfaces and ports. This comparison is the quickest way to answer "is this thing really isolated".

Creating a namespace from C

The unshare(2) system call detaches the calling process from a namespace it shares and puts it in a new one of the given type. Creating most types needs CAP_SYS_ADMIN, with one exception that makes the rest possible without root: a user namespace can be created by any unprivileged process, and inside the new user namespace the process has a full set of capabilities that apply to resources that namespace owns. The program below creates a user and a UTS namespace together, changes the hostname inside it and shows that the host's name is unaffected.

uts.cc
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static void print_hostname(const char *label)
{
    char name[64];
    gethostname(name, sizeof name);
    printf("%-22s %s\n", label, name);
}

int main(void)
{
    print_hostname("before unshare:");

    if (unshare(CLONE_NEWUSER | CLONE_NEWUTS) == -1) {
        perror("unshare");
        return 1;
    }

    const char *fake = "sandbox";
    if (sethostname(fake, strlen(fake)) == -1) {
        perror("sethostname");
        return 1;
    }
    print_hostname("inside the namespace:");
    return 0;
}
Shell
gcc -std=gnu17 -O2 -Wall -o uts uts.c
./uts
hostname
Text
before unshare:        build-box
inside the namespace:  sandbox
build-box

The program prints the old name, changes it, and prints the new one, and the shell's hostname afterwards shows the original build-box, because the change lived only in the namespace that exited with the process. This works as an ordinary user on a kernel that allows unprivileged user namespaces, which most distributions enable. Some, notably recent Ubuntu releases, restrict it with an AppArmor policy or the kernel.unprivileged_userns_clone and related settings, in which case unshare returns EPERM and you run the example as root or with the restriction relaxed.

The user namespace is what makes sethostname succeed. Changing the hostname needs CAP_SYS_ADMIN over the UTS namespace, and the process holds that capability inside the new user namespace that owns the new UTS namespace. It holds nothing over the host's namespaces, so the host is untouched.

How a container uses them

A container runtime does what the example does with more types at once. It calls clone or unshare with flags for mount, PID, network, UTS, IPC and usually user and cgroup namespaces. It sets up the filesystem, a root directory containing the image, with pivot_root in the new mount namespace. It creates a virtual network interface pair, moves one end into the new network namespace and configures it. It sets the hostname in the UTS namespace. Then it executes the container's command as PID 1 of the new PID namespace. Resource limits come from placing the process in a cgroup, and the privilege limits from capabilities, seccomp and no_new_privs, as in the earlier posts.

A container shares the host kernel, which is the key difference from a virtual machine. It starts in milliseconds because nothing boots, and it has the host kernel's attack surface, which is why the extra layers of seccomp, capabilities and security modules matter.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.