# Containers are Linux: namespaces, cgroups and Docker

A container is a Linux process: namespaces limit what it sees, cgroups what it uses, ulimits each process. Build one by hand, then see how Docker puts it together.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 16. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/linux/16-containers-on-linux

## What you will learn

- Explain a container as an ordinary Linux process with namespaces and cgroups
- Name the main namespaces and see them in /proc
- Limit memory and CPU with cgroups v2, and read what a process is using
- Read and raise ulimits such as the open files limit
- Explain how Docker, containerd and runc work together, and what an image is
- Run, inspect and limit a container, and debug it from the host

## A container is a process

**Why this lesson closes the course.** Sooner or later someone tells you "containers are like small
VMs", and then a container behaves in a way that makes no sense for a VM: you see its processes in
the host's `ps`, a memory limit kills it with no error message, or a "Too many open files" error
appears only in production. All of that makes sense once you know what a container really is, and
you already know most of it from this course.

Everything in this course applies inside containers, because a container _is_ a Linux process. The
kernel has no "container" object. It has two features that, used together, make a process look like
it has a machine to itself:

> **Figure.** A container on a Linux host. Inside one box, an ordinary process such as nginx. Around it, namespaces control what it can see: its own process IDs, network interfaces, mounts and filesystem, hostname, users and IPC. Below it, cgroups control what it can use: memory, CPU, number of processes and disk I/O. Under everything, the host's single shared kernel. To the side, the toolchain: docker, the client, talks to dockerd, which asks containerd, which starts runc to set up the namespaces and cgroups, and the image provides the filesystem.
>
> Namespaces: what it can see. cgroups: what it can use. One shared kernel underneath.

|                    | Virtual machine    | Container                               |
| ------------------ | ------------------ | --------------------------------------- |
| Kernel             | its own            | the host's, shared                      |
| Starts in          | tens of seconds    | milliseconds                            |
| Isolation          | hardware-level     | kernel features: strong, but one kernel |
| Seen from the host | one `qemu` process | the app's own processes, in `ps`        |

> **Video.** [Containers: Under The Hood (Vincent Batts)](https://www.youtube.com/watch?v=bG2WAHuVe_g) (DevNation)

## Namespaces: what a process can see

Think of namespaces as blinkers on a horse. The horse is still on the same road as everyone else,
but it can only see what's straight ahead. A process in its own namespaces is still running on the
same kernel as everything else, but it sees only _its_ processes, _its_ network card and _its_
files, so it behaves as if it had the machine to itself.

Each **namespace** gives a process its own view of one part of the system:

| Namespace               | Gives the process its own          | Container effect                              |
| ----------------------- | ---------------------------------- | --------------------------------------------- |
| `pid`                   | process numbers                    | its app is PID 1, it can't see host processes |
| `net`                   | interfaces, IPs, ports, routes     | its own `eth0` and `localhost`                |
| `mnt`                   | mounted filesystems                | sees the image's files as `/`                 |
| `uts`                   | hostname                           | `hostname` shows the container ID             |
| `user`                  | user and group IDs                 | root inside can be a normal user outside      |
| `ipc`, `cgroup`, `time` | shared memory, cgroup view, clocks |                                               |

```sh
$ ls /proc/self/ns                # every process has one of each
cgroup  ipc  mnt  net  pid  pid_for_children  time  time_for_children  user  uts
```

You can make namespaces yourself, without root, using `unshare` (`-r` maps you to root inside a new
user namespace):

```sh
$ unshare -r -u sh -c 'hostname box1; hostname'     # new UTS namespace: own hostname
box1
$ hostname                                          # the host is untouched
Elonerajeev
$ unshare -r -p -f --mount-proc ps -ef              # new PID namespace
UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 05:40 ?        00:00:00 ps -ef
```

Inside the new PID namespace, `ps` is PID 1 and sees nothing else. That's exactly why `docker exec
… ps` shows only the container's processes. `nsenter` does the reverse: it runs a command inside an
existing process's namespaces, which is how you debug a container that has no shell.

Use PID and network namespaces to separate process numbering and interfaces, while remembering that they do
not limit resource consumption. Namespaces are one isolation layer, not a substitute for keeping the kernel
patched or limiting privileges. A common mistake is assuming a process with a different PID 1 has its own
kernel; the host still schedules it and handles its system calls.

## cgroups: what a process can use

**Control groups** put processes in a tree and limit each branch: memory, CPU, number of processes,
disk I/O. Modern distributions use **cgroups v2**, one tree under `/sys/fs/cgroup`:

```sh
$ stat -fc %T /sys/fs/cgroup              # cgroup2fs means v2
cgroup2fs
$ cat /proc/self/cgroup                   # which cgroup this shell is in
$ systemd-cgls --no-pager | head          # the whole tree: systemd organises it
$ systemd-cgtop                           # live use per cgroup, like top
```

systemd puts every service in its own cgroup, which is why `systemctl status` shows a service's
memory. You can limit any command or service the same way a container runtime does:

```sh
$ systemd-run --user --scope -p MemoryMax=50M sh -c 'cat /sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)/memory.max'
52428800
```

| File in the cgroup | Controls                          | Docker flag        | systemd setting    |
| ------------------ | --------------------------------- | ------------------ | ------------------ |
| `memory.max`       | memory limit, then the OOM killer | `--memory 512m`    | `MemoryMax=512M`   |
| `cpu.max`          | CPU time per period               | `--cpus 1.5`       | `CPUQuota=150%`    |
| `pids.max`         | number of processes               | `--pids-limit 200` | `TasksMax=200`     |
| `memory.current`   | memory used now                   | `docker stats`     | `systemctl status` |

When a cgroup hits `memory.max`, the kernel's OOM killer kills a process in it with `SIGKILL`: exit code
137 (128 + 9). `docker inspect` then shows `"OOMKilled": true`, and `journalctl -k` has the kill.

## ulimits: limits per process

**The incident this prevents.** Your API works fine in testing. On launch day, traffic climbs, and
at a few thousand users the logs fill with `Too many open files` and new requests fail. Nothing is
wrong with the code. Every network connection uses a "file descriptor", and the process hit its
limit on how many it may hold open at once.

**ulimits** (resource limits) cap a single process, not a group. The one that bites in production is
**open files**: every file, socket and connection uses one file descriptor.

```sh
$ ulimit -n                       # open-files limit for this shell
1048576
$ ulimit -a                       # every limit
$ grep -E "processes|open files" /proc/$(pgrep -o nginx)/limits   # a running process's limits
Max processes             15109                15109                processes
Max open files            1048576              1048576              files
```

Each limit has a **soft** value (what applies) and a **hard** value (the ceiling a normal user may
raise the soft one to). Where to raise them:

| For               | Set it in                                                                       |
| ----------------- | ------------------------------------------------------------------------------- |
| a systemd service | `LimitNOFILE=65536` in the unit's `[Service]`, then `daemon-reload` and restart |
| a container       | `docker run --ulimit nofile=65536:65536 …`                                      |
| user logins       | `/etc/security/limits.conf` (`deploy soft nofile 65536`)                        |

"Too many open files" under load means this limit, not the disk. Note that `limits.conf` doesn't
apply to systemd services: they only read their unit file.

Check both soft and hard values for the running process, then raise the limit in the configuration that
starts it. Use a systemd unit setting for a system service, Docker's `--ulimit` for a container, or
`limits.conf` for login sessions. A common mistake is changing `limits.conf` and expecting a systemd service
to inherit it; restart the process after changing its launch configuration.

## Container runtimes: who does what

`docker run` passes through several programs, each with one job. Knowing them helps when one breaks,
and it's what Kubernetes uses too:

```text
docker (CLI)  →  dockerd           images, networks, volumes, the API
              →  containerd        pulls images, runs and watches containers
              →  runc              creates namespaces and cgroups, starts the process, exits
              →  your process      PID 1 inside the container
```

- An **image** is a stack of read-only filesystem layers plus settings (command, environment). Running
  it adds a thin writable layer on top, using **overlayfs**: delete the container and that layer goes
  too. Data you keep belongs in a **volume**.
- **OCI** (the Open Container Initiative) standardises images and runtimes, so an image built with
  Docker runs on Podman, containerd or Kubernetes unchanged.
- **Podman** runs the same images without a daemon, and rootless by default; `podman` accepts the
  same commands as `docker`.

## Docker on a Linux server

Once the kernel concepts are clear, Docker provides a convenient interface to create namespaces, cgroups,
images and networks. The daemon accepts CLI requests, then starts containers from image configuration. Its
socket is powerful: anyone who can use it can often control the host, so group membership is an administrative
permission.

Install Docker from the distribution or vendor repository, configure the daemon deliberately, and use
resource limits for workloads that share a host. Inspect a container's host PID when kernel-level debugging
is needed. A common mistake is adding an account to the `docker` group as if it were an ordinary developer
group; that access can be equivalent to root.

```sh
$ sudo apt install docker.io                      # or Docker's own repository (Packages lesson)
$ sudo usermod -aG docker deploy                  # let deploy use docker (log in again)
$ docker run -d --name web -p 8080:80 --memory 256m --cpus 1 --restart unless-stopped nginx:1.27
$ docker ps                                       # running containers
$ docker logs -f web                              # its stdout and stderr
$ docker exec -it web sh                          # a shell inside its namespaces
$ docker stats --no-stream                        # live CPU and memory per container
$ docker inspect web --format '{{.State.Pid}} {{.State.OOMKilled}}'
```

> **The docker group is root.** Anyone in the `docker` group can start a container that mounts the host's `/` and change anything on the server, so membership is effectively root access. Add only people and service accounts that would be allowed `sudo` anyway, or use rootless Docker or Podman where that isn't acceptable.

From the host, the container is just a process. Its PID from `docker inspect` works with every tool
in this course: `ps -fp <pid>`, `cat /proc/<pid>/limits`, `sudo nsenter -t <pid> -n ss -tlnp` (its
network, your tools).

> **The docker group is root.** Anyone in the `docker` group can start a container that mounts the host's `/` and change any file on it. Treat membership like sudo. For untrusted workloads use rootless Docker or Podman.

> **In production.** Always set a memory limit: one leaking container without one can take the whole host's memory. Pin image versions (`nginx:1.27`, not `latest`), run as a non-root user inside the image, log to stdout so `docker logs` and your log shipper see it, and keep data in volumes, never in the container.

> **Video.** [Docker Essentials (Part 4) - Running Containers](https://www.youtube.com/watch?v=VevE65N3BOs) (Learn Linux TV)

## Mission: Build a container by hand

Without Docker, start a shell that has its own hostname, its own process tree and a 50 MB memory limit. Prove each one from inside, and prove the host can still see it as an ordinary process.

- You need: Any Linux machine with systemd and cgroups v2 (no root needed)
- You'll have: A shell that is, to the kernel, a container

```sh
$ systemd-run --user --scope -q -p MemoryMax=50M \
    unshare -r -u -p -f --mount-proc sh -c '
      hostname box1
      echo "hostname: $(hostname)"
      echo "memory:   $(cat /sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)/memory.max) bytes"
      ps -eo pid,comm
    '
hostname: box1
memory:   52428800 bytes
    PID COMMAND
      1 sh
      6 ps
```

Three kernel features, no container software: a UTS namespace for the hostname, a PID namespace (the
shell is PID 1 and sees only itself and `ps`), and a cgroup capping memory at 50 MB. Docker
adds a network namespace, a mount namespace with the image as `/`, and the tooling to ship it, but
underneath it's this. Run `hostname` afterwards: the host's name never changed.

## Try it

- List a process's namespaces with `ls -l /proc/self/ns`.
- Start a shell with its own hostname using `unshare -r -u sh`, change the hostname, and check the host's name hasn't changed.
- See PID 1 in a new PID namespace with `unshare -r -p -f --mount-proc ps -ef`.
- Check which cgroup version you have with `stat -fc %T /sys/fs/cgroup`.
- Read your open-files limit with `ulimit -n` and a running process's limits in `/proc/<pid>/limits`.
- On a machine with Docker, run `docker run --rm -m 100m alpine cat /sys/fs/cgroup/memory.max`.

## Quiz

1. What is a container, from the Linux kernel's point of view?
   - A small virtual machine with its own kernel
   - **An ordinary process (or group of processes) with its own namespaces and cgroup limits, sharing the host's kernel** (answer)
   - A special kind of file
   Why: There's no container object in the kernel. Namespaces change what the process sees, cgroups limit what it uses, and the host kernel runs it. That's why containers start in milliseconds and why a kernel bug affects them all.

2. Which namespace makes a process inside a container see itself as PID 1?
   - **The PID namespace** (answer)
   - The network namespace
   - The user namespace
   Why: A new PID namespace numbers its processes from 1. On the host, the same process has a normal, larger PID that ps shows.

3. A container keeps getting killed with exit code 137. What do you check first?
   - **Its memory limit: 137 is 128 + 9, killed by SIGKILL, usually the out-of-memory killer hitting the cgroup limit** (answer)
   - The network
   - The image tag
   Why: docker inspect shows "OOMKilled": true when that happened. Raise the limit or fix the memory use; the kernel log shows the OOM kill too.

4. Nginx logs "Too many open files" under load. Which limit is it hitting?
   - The disk size
   - **The open-files ulimit (nofile) for the process** (answer)
   - The cgroup CPU limit
   Why: Every connection is a file descriptor. Raise it for a service with LimitNOFILE= in its unit file, or --ulimit nofile= for a container.

5. Who actually creates the namespaces and cgroups when you run docker run?
   - The docker command itself
   - **runc (the OCI runtime), started by containerd, which dockerd asks** (answer)
   - systemd
   Why: docker is a client; dockerd manages images and networks; containerd manages container life cycles; runc does the kernel setup and then gets out of the way. Kubernetes uses containerd and runc too, without dockerd.

## Resources

- [namespaces(7) manual](https://manpages.ubuntu.com/manpages/noble/man7/namespaces.7.html) (Ubuntu manpages)
- [Control Group v2: the kernel documentation](https://docs.kernel.org/admin-guide/cgroup-v2.html) (Linux kernel)
- [Docker: resource constraints](https://docs.docker.com/engine/containers/resource_constraints/) (Docker)
- [Open Container Initiative: runtime and image specs](https://opencontainers.org/) (OCI)
- [getrlimit(2): resource limits](https://manpages.ubuntu.com/manpages/noble/man2/getrlimit.2.html) (Ubuntu manpages)
