cgroups & Namespaces

cgroups v1 vs v2, resource limits, container isolation mechanics, and namespace types.

Overview

Control groups (cgroups) and namespaces are the two kernel features that make containers possible. Cgroups provide resource limiting; namespaces provide isolation.

cgroups (v2)

Cgroups v2 organise processes into a hierarchy with resource controllers: - cpu — CPU time share and quota - memory — max RSS, swap, page cache - io — disk bandwidth - pids — max number of processes

When a cgroup's memory limit is exceeded, the kernel OOM-kills a process within that cgroup.

Linux Namespaces

  • pid — container gets its own PID 1
  • net — own network interfaces and routing table
  • mnt — own filesystem mount points
  • uts — own hostname and domainname
  • ipc — own System V IPC
  • user — UID/GID mapping (uid 0 in container maps to unprivileged uid on host)

Containers Are Just Processes

A container is a process running in its own set of namespaces and controlled by a cgroup. There is no container kernel — the same host kernel serves all containers. This is why container isolation is weaker than VM isolation: a container escape exploit can reach the host kernel directly.

Key concepts

cgroup memory.max
Hard limit on memory usage in cgroup v2. In Docker: --memory flag. In Kubernetes: resources.limits.memory.
PID namespace
Each container sees its own PID space starting at 1. Container PID 1 maps to a higher PID on the host.
Network namespace
Each container gets its own network stack: lo, virtual ethernet pair (eth0 inside, vethXXXX on host), own routing table.
User namespace
Maps UIDs inside the namespace to different UIDs on the host. Rootless containers: uid=0 inside maps to unprivileged uid on host.
Cgroup v2 unified hierarchy
Single cgroup tree with all resource controllers. Required for Kubernetes cgroup v2 support since Kubernetes 1.25.

When to use it

  • Explaining the technical difference between containers and VMs
  • Debugging why a container is hitting its memory limit even though the app seems fine
  • Designing rootless containers with user namespace mapping for defense in depth

Interview questions

  • How do Linux namespaces enable container isolation? Walk through each namespace type.

Sign up free to read the full topic

More Linux topics

Start free on Cariara · Coding problems · System design studio