# Under the hood: namespaces, cgroups and layered filesystems

What Docker does when it starts a container: namespaces hide the rest of the machine, cgroups cap its resources, and an overlay filesystem stacks a writable layer on a shared image.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 2. About 30 minutes, beginner. Source: https://devops.rajeev.pro/courses/docker/02-under-the-hood

## What you will learn

- Explain a container as an ordinary Linux process with namespaces, cgroups and its own filesystem view
- See the same container process from inside (PID 1) and from the host (a normal PID)
- Turn docker run flags such as --memory and --cpus into the cgroup files they set
- Explain image layers, the container's writable layer and copy-on-write
- Read docker diff, and explain why data written inside a container disappears with it

## A container is a process

Before containers, teams copied an application and its dependencies onto each server, then hoped
the next server had the same libraries and settings. Virtual machines made environments more
repeatable, but each one needed a full guest operating system. Docker gives an app a repeatable
filesystem and isolates its processes without starting another kernel.

There is no special "container" object inside the Linux kernel. When you run `docker run`, the
Docker Engine asks the kernel to start an ordinary process with isolation and resource controls.
Namespaces limit what that process can see. Control groups (cgroups) limit what it can use. The
overlay filesystem gives it a root directory assembled from image layers plus a private writable
layer. In practice: Docker receives the run request, prepares those boundaries, starts the process,
and reports the container's state. The process remains visible to host tools such as `ps` and
`top`.

You'll compare its PID and namespace IDs from inside and outside the container, then inspect its
resource limits and filesystem changes. The Linux course's _Containers on Linux_ lesson builds
similar isolation pieces directly; this lesson shows what Docker configures for you.

```sh
$ docker run -d --name cow alpine:3.22 sleep 300
$ docker exec cow ps                         # inside: the app is PID 1
PID   USER     TIME  COMMAND
    1 root      0:00 sleep 300
    8 root      0:00 ps
$ docker inspect -f '{{.State.Pid}}' cow     # the same process, seen from the host
215435
$ ps -o pid,user,cmd -p 215435
    PID USER     CMD
 215435 root     sleep 300
```

Same process, two numbers. That's the whole trick, and it's why host tools such as `ps`, `top`,
`kill` and `strace` work on containers.

> **Video.** [Containers - Namespaces, Cgroups and Overlay Filesystem](https://www.youtube.com/watch?v=wJdDWc6zO4U) (All Things Systems)

## Namespaces: what the container can see

Without namespaces, a process could see the host's process list, network interfaces and mount
points. That makes unrelated applications harder to separate and can expose host details. A Linux
namespace gives a process and its descendants a separate view of one system resource. Docker asks
the kernel to place the new process in selected namespaces when it starts.

For example, the PID namespace gives the container its own process numbering, so its main process
can be PID 1 inside while having a different host PID. The network namespace has its own interfaces
and loopback address; publishing a port is a separate Docker networking step. The mount namespace
provides a separate view of mounted filesystems, while the UTS namespace controls the hostname.
Namespaces isolate views, but they do not by themselves limit CPU or memory.

Compare namespace IDs on the host and in a container:

```sh
$ readlink /proc/self/ns/pid /proc/self/ns/net      # on the host
pid:[4026532219]
net:[4026531840]
$ docker run --rm alpine:3.22 sh -c 'readlink /proc/self/ns/pid; readlink /proc/self/ns/net'
pid:[4026532234]
net:[4026532236]
```

Different numbers mean different namespaces:

| Namespace               | The container gets                   | You notice it as                                                |
| ----------------------- | ------------------------------------ | --------------------------------------------------------------- |
| `pid`                   | its own process list                 | `ps` shows only its processes, the app is PID 1                 |
| `net`                   | its own interfaces, IP and ports     | it has its own `localhost`; ports must be published (lesson 10) |
| `mnt`                   | its own mounts                       | `/` is the image, not the host                                  |
| `uts`                   | its own hostname                     | `docker run --hostname shop … hostname` prints `shop`           |
| `ipc`, `user`, `cgroup` | shared memory, user IDs, cgroup view | rarely, until something needs them                              |

The IDs are kernel handles, not names you configure in Docker. A different ID shows the process is
attached to a different namespace instance. It does not mean the container has a separate kernel:
both processes still ask the host kernel to do work. Use namespaces for process and network
separation; use a VM when you need a separate guest kernel or a stronger boundary between tenants.
One common mistake is assuming a separate network namespace automatically makes a service
reachable. Containers still need an appropriate network and, for traffic from outside the host, a
published port.

## cgroups: what the container can use

Isolation alone doesn't stop one busy container from consuming all the host's memory or CPU. Linux
control groups, usually shortened to **cgroups**, account for and constrain resource use by a group
of processes. Docker turns run options into cgroup settings when it creates the container.

The memory limit is a hard ceiling: if the container tries to use more, the kernel may invoke its
out-of-memory (OOM) handling and kill a process. The CPU limit is a quota over a period, so the
container can use a fraction of a core on average. A PID limit caps the number of processes it can
create. These settings protect neighboring workloads, but an overly small limit can also make a
healthy application slow or cause it to exit.

The following command sets memory and CPU limits, then reads the corresponding cgroup values:

```sh
$ docker run --rm --memory 128m --cpus 0.5 alpine:3.22 \
    sh -c 'cat /sys/fs/cgroup/memory.max /sys/fs/cgroup/cpu.max'
134217728
50000 100000
```

| Flag               | cgroup file                | Means                                                                       |
| ------------------ | -------------------------- | --------------------------------------------------------------------------- |
| `--memory 128m`    | `memory.max` = `134217728` | 128 × 1024 × 1024 bytes; over it, the OOM killer stops a process (exit 137) |
| `--cpus 0.5`       | `cpu.max` = `50000 100000` | 50 ms of CPU time in every 100 ms: half a core                              |
| `--pids-limit 200` | `pids.max` = `200`         | stops fork bombs                                                            |

Without limits, one leaking container can use all the host's memory and take every other container
down with it. `docker stats` shows live usage against these limits.

Choose limits from measurements and the application's expected load, then monitor throttling and
OOM events. A CPU quota slows work rather than reserving a dedicated core. For a workload that
needs a guaranteed share, also consider CPU shares or reservations supported by the runtime or
orchestrator. A common mistake is to copy a tiny example limit into production; check the actual
cgroup values and application metrics before deciding whether a limit is too high or too low.

## Layers and copy-on-write

An **image** is a stack of read-only **layers**. Starting a container adds one thin **writable layer**
on top, and the kernel's **overlay filesystem** merges them into the `/` the container sees:

```sh
$ docker run --rm alpine:3.22 sh -c 'mount | head -1'
overlay on / type overlay (rw,relatime,lowerdir=…/snapshots/227/fs:…/snapshots/218/fs,upperdir=…/snapshots/228/fs,workdir=…)
```

`lowerdir` is the read-only layers; `upperdir` is this container's writable layer.

> **Figure.** Animated. Container a starts from the alpine:3.22 image, whose layer is read-only and shared. Reading /etc/os-release is served straight from the image layer. Writing /root/note.txt creates the file in container a's own writable layer. Deleting /etc/motd records a whiteout in that layer that hides the file; the image is unchanged. Container b, from the same image, gets its own empty writable layer and shares the image layer. Removing container a deletes its writable layer, so note.txt is lost, while the image is untouched.
>
> Reads come from the shared image. Writes, and even deletes, only touch the container's own layer, which dies with it.

`docker diff` lists what a container changed compared with its image:

```sh
$ docker diff cow
C /root
A /root/note.txt
C /etc
A /etc/resolv.conf.bak
D /etc/motd
```

**A**dded, **C**hanged, **D**eleted. Writing a file that exists in the image first **copies** it up into
the writable layer (copy-on-write), then changes the copy. Deleting one adds a "whiteout" marker that
hides it. The image itself never changes, which is why a hundred containers can share one image, and
why anything a container writes is lost when you remove it.

```sh
$ docker image history alpine:3.22 --format '{{.Size}}\t{{.CreatedBy}}'
0B      CMD ["/bin/sh"]
8.97MB  ADD alpine-minirootfs-3.22.6-x86_64.tar.gz /
```

> **In production.** Treat the writable layer as scratch space. Logs go to stdout and stderr (read with `docker logs`), data goes to volumes, and the container itself stays disposable: you replace it, you don't repair it.

## Mission: Prove a container is just a process

Start an alpine container with memory and CPU limits, then prove from the outside and the inside that it is a host process with its own PID numbering, its own namespaces, the cgroup limits you set, and a writable layer that records every change.

- You need: Docker on a Linux host (or Docker Desktop)
- You'll have: Notes showing host PID vs PID 1, two namespace IDs, the cgroup values and docker diff

```sh
$ docker run -d --name probe --memory 128m --cpus 0.5 alpine:3.22 sleep 600
$ docker exec probe ps                                   # PID 1 inside
$ ps -o pid,cmd -p "$(docker inspect -f '{{.State.Pid}}' probe)"   # a normal PID outside
$ docker exec probe readlink /proc/self/ns/pid && readlink /proc/self/ns/pid
$ docker exec probe sh -c 'cat /sys/fs/cgroup/memory.max /sys/fs/cgroup/cpu.max'
134217728
50000 100000
$ docker exec probe sh -c 'echo hi > /root/note.txt && rm /etc/motd'
$ docker diff probe
C /root
A /root/note.txt
C /etc
D /etc/motd
$ docker rm -f probe
```

The two `pid:[…]` numbers differ, `memory.max` is exactly 128 × 1024 × 1024, and `docker diff` lists your
two changes. After `docker rm`, start a fresh container from the same image: `/root/note.txt` isn't there
and `/etc/motd` is back.

## Try it

- Run `docker run --rm alpine:3.22 ps` and explain why the list is so short.
- Compare `readlink /proc/self/ns/pid` on the host with the same command inside a container.
- Start a container with `--memory 128m --cpus 0.5` and read `/sys/fs/cgroup/memory.max` and `cpu.max` inside it.
- Start a container, find its host PID with `docker inspect -f '{{.State.Pid}}'`, and look at it with `ps -p`.
- Create, change and delete files in a running container, then read `docker diff`.
- Run `mount | head -1` inside a container and find the lowerdir and upperdir.

## Quiz

1. Inside a container, ps shows the app as PID 1. What PID does it have on the host?
   - Also 1
   - **A normal host PID, such as 215435: PID 1 is only how its own PID namespace numbers it** (answer)
   - It has no PID on the host
   - Always 0
   Why: A container is a host process. docker inspect -f {{.State.Pid}} shows its host PID, and host tools like ps, top and kill work on it.

2. What does docker run --memory 128m actually change?
   - The image
   - **The memory.max file of the container's cgroup, to 134217728 bytes** (answer)
   - The host's RAM
   - Nothing until restart
   Why: Docker writes the limit into cgroups v2. If the processes go over it, the kernel's OOM killer stops one of them (exit code 137).

3. Two containers run from the same image. How much extra disk does the second one use at start?
   - A full copy of the image
   - **Almost nothing: both share the read-only image layers and each gets an empty writable layer** (answer)
   - Twice the image size
   - It depends on the CPU
   Why: That's why containers start in milliseconds and a host can run hundreds from one image.

4. A container deletes /etc/motd, which came from the image. What happens to the image?
   - The file is removed from the image
   - **Nothing: a whiteout in the container's writable layer hides the file; the image is unchanged** (answer)
   - The image is rebuilt
   - Docker refuses the delete
   Why: Image layers are read-only. docker diff shows D /etc/motd for that container only.

5. You docker rm a container that wrote logs to /var/log/app. Where are the logs?
   - In the image
   - **Gone: they lived in the container's writable layer, which is deleted with it** (answer)
   - In /tmp on the host
   - In the registry
   Why: Data that must outlive the container belongs in a volume or bind mount, or logs go to stdout for docker logs (lesson 6).

## Resources

- [Docker Docs: storage drivers and copy-on-write](https://docs.docker.com/engine/storage/drivers/) (Docker Docs)
- [Docker Docs: resource constraints](https://docs.docker.com/engine/containers/resource_constraints/) (Docker Docs)
- [namespaces(7) manual](https://manpages.ubuntu.com/manpages/noble/man7/namespaces.7.html) (Ubuntu manpages)
- [Linux kernel: overlay filesystem](https://docs.kernel.org/filesystems/overlayfs.html) (Linux kernel)
