Linux Namespaces and cgroups: Kernel Isolation, Resource Limits, and Breakout Risks
How Linux namespaces isolate kernel visibility and cgroups v2 enforce CPU, memory, and PID quotas to prevent noisy neighbors and breakouts.

At 2
AM, restarting a single misbehaving worker container on a shared Linux host can freeze your SSH session, stall health checks, and knock neighboring services offline. Operators often suspect a kernel panic or a failing hypervisor, only to discover that a runaway process inside the container consumed every CPU cycle and filled host memory until the SSH daemon starved. The surprise fades once you examine what a container actually is: not a lightweight virtual machine with its own operating system, but one or more ordinary Linux processes running directly on the shared host kernel.To make those ordinary processes behave like isolated machines, Linux container runtimes rely on two foundational kernel primitives: namespaces and control groups (cgroups). Think of a shared office building where every tenant company shares the same foundation, plumbing, and building superintendent. Namespaces erect soundproof walls and frosted glass so each tenant sees only its own conference rooms, internal phone extensions, and directory signs, unaware of the neighbors next door. Control groups act as the utility meters and circuit breakers on the building's main panel, capping how much electricity (CPU time), water (memory and disk I/O), and lobby occupancy (process slots) any single tenant can draw before a breaker trips.
Understanding how these two subsystems interact under the hood separates fragile container deployments from production-grade isolation. Even more importantly, it explains a hard truth of container security: hiding resources with namespaces and throttling usage with cgroups still leaves every container speaking directly to the same building superintendent, the Linux kernel. Closing the remaining gaps requires pairing namespaces and cgroups with credential mapping, Linux capabilities, syscall filtering, and careful runtime hygiene.
How do Linux namespaces partition what a container sees?
Linux namespaces wrap global kernel resources inside scoped abstractions so that processes inside a namespace observe a private view of process trees, filesystems, hostnames, and network stacks. When a process calls clone(), unshare(), or setns(), the kernel swaps pointers inside the task's struct nsproxy and credential structures (struct cred), causing subsequent system calls to resolve names and IDs against those private tables rather than the host's global state.
Before Docker popularized containers in 2013, kernel engineers spent years building namespace primitives into mainline Linux between versions 2.6.15 and 2.6.26 (drawing heavily on earlier OpenVZ isolation designs from 2005). Every running Linux task belongs to one instance of each supported namespace type, even on a bare-metal workstation that has never run Docker. You can inspect those attachments directly in /proc/<pid>/ns/, where symbolic links expose opaque kernel inode identifiers such as pid:[4026531836] and net:[4026531992]. Two processes share a view of a subsystem if and only if their links point to the same namespace inode.
mermaid\nflowchart TD\n HostTask[\"Host Process (struct task_struct)\"] --> Clone[\"clone() or unshare() with CLONE_NEW* flags\"]\n Clone --> NsProxy[\"Container struct nsproxy\"]\n NsProxy --> PidNS[\"PID Namespace (PID 1 init tree)\"]\n NsProxy --> MntNS[\"Mount Namespace (pivot_root filesystem)\"]\n NsProxy --> NetNS[\"Network Namespace (veth, routing, nftables)\"]\n NsProxy --> UserNS[\"User Namespace (UID 0 mapped to host UID 100000)\"]\n PidNS --> Kernel[\"Shared Host Linux Kernel\"]\n MntNS --> Kernel\n NetNS --> Kernel\n UserNS --> Kernel\n
Modern Linux kernels implement eight distinct namespace types, each partitioning a specific slice of global operating system state. A common mistake among junior engineers is treating "a container namespace" as a single switch, when in reality forgetting even one flag leaves a subtle information leak or privilege bridge open.
| Namespace | clone() Flag |
Isolated Kernel Resource | Common Misconfiguration Pitfall |
|---|---|---|---|
Mount (mnt) |
CLONE_NEWNS |
Filesystem mount table and root directory | Forgetting pivot_root() or leaving host bind mounts writable |
Process ID (pid) |
CLONE_NEWPID |
Hierarchical process ID number space | Failing to mount a private /proc, exposing host processes |
Network (net) |
CLONE_NEWNET |
Network devices, IP stacks, sockets, routing, firewall rules | Sharing --network=host, exposing loopback admin services |
User (user) |
CLONE_NEWUSER |
UIDs, GIDs, and capability scopes | Omitting UID mapping, leaving container root equal to host root |
IPC (ipc) |
CLONE_NEWIPC |
System V IPC and POSIX message queues | Sharing host IPC namespace, allowing shared-memory tampering |
UTS (uts) |
CLONE_NEWUTS |
Hostname and NIS domain name | Minor impact alone, breaks service identity if shared |
Cgroup (cgroup) |
CLONE_NEWCGROUP |
Virtualized view of /proc/self/cgroup hierarchy |
Exposing host cgroup paths without virtualization |
Time (time) |
CLONE_NEWTIME |
CLOCK_MONOTONIC and CLOCK_BOOTTIME offsets |
Rare container clock skew after live restore if omitted |
Among all eight, the PID, Mount, and User namespaces create the tightest architectural interdependence. When you create a new PID namespace, the first process spawned inside it receives PID 1 in that child namespace while simultaneously holding a normal high-numbered PID (such as 28419) in the host's root PID namespace. The host can still inspect and signal the container process because PID namespaces form a strict tree: parent namespaces see all descendants, while children cannot see upward or sideways. However, tools like ps and top do not query a "list processes" syscall; they read directories inside /proc. Unless the runtime pairs the PID namespace with a fresh Mount namespace and mounts a new proc filesystem specifically for that namespace, ps inside the container will happily read the host's /proc and display every host process.
The User namespace governs Linux credentials, and understanding it requires looking at how the kernel decides whether any action is permitted. When a subject (a task) acts on an object (a file inode, socket, or another task), Linux evaluates the task's subjective context (Effective UID/GID, Filesystem UID/GID, supplementary groups, and effective Linux capabilities) against the object's objective context (ownership UID/GID, discretionary ACLs, and mandatory access control labels). Without a User namespace, UID 0 inside a container is identical to UID 0 on the host. If that container ever accesses a host-owned inode through a misconfigured bind mount or kernel bug, the kernel treats it as full system root.
With a User namespace enabled, the kernel consults per-namespace mapping tables stored in /proc/<pid>/uid_map and /proc/<pid>/gid_map. Container UID 0 can be mapped to an unprivileged host UID such as 100000. Inside the container, the process holds capabilities scoped strictly to resources created inside that User namespace, allowing package managers or build tools to change file ownership seamlessly. Outside the container, every file it creates or signal it tries to send carries host UID 100000, neutralizing its authority over host-owned files.
How do cgroups v2 enforce CPU, memory, and PID limits?
Control groups v2 organize every Linux task into a single unified hierarchy under /sys/fs/cgroup, where kernel resource controllers measure consumption and enforce hard or proportional ceilings on CPU time, memory, disk I/O, and process creation. While namespaces prevent a container from seeing or touching another workload's objects, cgroups prevent a single noisy or malicious workload from exhausting shared hardware and causing denial of service.
The original cgroups implementation (merged in Linux 2.6.24) suffered from an awkward architectural flaw: each resource controller maintained its own separate directory tree. A process could belong to cgroup A for CPU, cgroup B for memory, and cgroup C for block I/O. That fragmentation made coordinated accounting nearly impossible. For example, when an application wrote heavily to disk, dirty memory pages were buffered in the kernel page cache and flushed asynchronously by kernel worker threads, bypassing the originating container's blkio throttle entirely.
Modern Linux distributions and container runtimes standardize on cgroups v2, which replaces fragmented trees with one unified hierarchy and enforces the "no internal processes" rule. A process lives exclusively in leaf cgroups, non-leaf parent nodes only delegate budgets downward to children, and the memory and io controllers cooperate so asynchronous page-cache writeback is accurately billed back to the container that dirtied the pages.
mermaid\nsequenceDiagram\n participant Runtime as \"Container Runtime (runc)\"\n participant Cgroup as \"cgroups v2 (/sys/fs/cgroup)\"\n participant Kernel as \"Linux Kernel Scheduler & MM\"\n participant App as \"Container Process (PID 1)\"\n\n Runtime->>Cgroup: \"Create leaf cgroup and write cpu.max, memory.max, pids.max\"\n Runtime->>Kernel: \"clone() with CLONE_NEW* namespaces and user_map\"\n Runtime->>Cgroup: \"Write container PID to cgroup.procs\"\n Kernel-->>App: \"Start execution inside isolated namespaces\"\n App->>Kernel: \"Allocate burst memory beyond memory.high\"\n Kernel->>App: \"Throttle via direct memory reclaim (PSI stall)\"\n App->>Kernel: \"Allocate past memory.max ceiling\"\n Kernel->>App: \"Invoke cgroup-local OOM killer (host sshd stays intact)\"\n
Three controllers carry most of the security and reliability weight in multi-tenant production environments:
- CPU bandwidth control (
cpu.maxandcpu.weight): Under cgroups v2, relative shares usecpu.weight(1 to 10000, default 100) when CPUs are contended, while hard caps usecpu.maxformatted as$MAX $PERIODin microseconds. Writing20000 100000grants the cgroup 20,000 microseconds (20ms) of total CPU execution time across all cores during every 100,000 microsecond (100ms) scheduling period, equivalent to 20% of one core. Once the cgroup exhausts its 20ms quota inside that window, the kernel scheduler suspends all runnable threads in the cgroup until the next period begins. - Memory limits and pressure (
memory.high,memory.max, andmemory.swap.max): Unlike CPU throttling, hitting a hard memory ceiling cannot simply pause a process indefinitely. Settingmemory.highcreates a soft throttle: as usage crosses that line, the kernel forces the allocating task into synchronous page reclaim, slowing it down cleanly and exposing stalls inmemory.pressure. If memory continues rising pastmemory.max, the kernel triggers a cgroup-scoped Out-Of-Memory (OOM) killer that terminates processes exclusively inside that cgroup, leaving host daemons likesshdand neighboring containers untouched. Settingmemory.swap.maxto0prevents containers from dodging memory caps by thrashing host swap. - Process count caps (
pids.max): Even a small container with a strict memory cap can destabilize a host by spawning thousands of tiny processes in a fork bomb, exhausting the global kernel PID space or slab caches fortask_structallocations. Writing an explicit ceiling such as128topids.maxinstructs the kernel'sfork()andclone()paths to fail cleanly withEAGAINonce the cgroup hits that threshold, containing fork bombs instantly.
Building container isolation from scratch: vulnerable vs. hardened Linux execution
Walking through raw Linux primitives directly at the command line strips away the abstraction of docker run and shows how namespaces and cgroups cooperate step by step. A process started naively on a Linux host shares global visibility and unlimited resources, whereas wrapping the exact same workload in explicit cgroup limits and namespace flags creates a tight runtime boundary.
Vulnerable baseline: unconfined host execution
When a service or ad-hoc worker runs directly in the host's default namespace and root cgroup, nothing separates it from neighboring processes or host administration tools.
bash\n# Unconfined worker executing directly in host namespaces and root cgroup\npython3 -c 'import time; data = bytearray(512 * 1024 * 1024); time.sleep(30)' &\n\n# Any process on the host is visible, and CPU/RAM usage hits the host globally\nps -eo pid,uid,comm | head -n 10\n
If that Python snippet scales out its allocation or spawns infinite worker threads, the host's global OOM killer may eventually choose sshd, a database daemon, or the container runtime itself as its victim depending on oom_score heuristics. Worse, the process reads host-wide /proc entries and shares the host's network interfaces and mount tree.
Hardened baseline: cgroups v2 quotas paired with isolated namespaces
To enforce a durable boundary manually, you create the cgroup and write its limits first, attach the target shell PID before spawning child workloads, and isolate visibility with unshare. Notice the order of operations: attaching the parent shell to cgroup.procs guarantees that every child forked inside the new namespace automatically inherits the cgroup membership without a race window.
bash\n# 1. Create a cgroups v2 leaf and enforce 20% CPU, 192MiB soft / 256MiB hard RAM, 64 PIDs\nsudo mkdir -p /sys/fs/cgroup/app-sandbox\necho \"20000 100000\" | sudo tee /sys/fs/cgroup/app-sandbox/cpu.max\necho \"201326592\" | sudo tee /sys/fs/cgroup/app-sandbox/memory.high\necho \"268435456\" | sudo tee /sys/fs/cgroup/app-sandbox/memory.max\necho \"0\" | sudo tee /sys/fs/cgroup/app-sandbox/memory.swap.max\necho \"64\" | sudo tee /sys/fs/cgroup/app-sandbox/pids.max\n\n# 2. Launch an isolated environment with unprivileged userns mapping and private /proc\nsudo sh -c 'echo $ > /sys/fs/cgroup/app-sandbox/cgroup.procs && exec unshare --pid --fork --mount-proc --uts --ipc --net --user --map-root-user /bin/sh'\n
Inside the resulting isolated shell, inspecting the process table, UID mapping, and cgroup telemetry confirms that both isolation visibility and resource accounting are active.
console\n# Inside the isolated shell:\n$ ps -ef\nUID PID PPID C STIME TTY TIME CMD\nroot 1 0 0 14:20 pts/0 00:00:00 /bin/sh\nroot 2 1 0 14:20 pts/0 00:00:00 ps -ef\n\n$ cat /proc/self/uid_map\n 0 0 1\n\n$ cat /sys/fs/cgroup/app-sandbox/pids.current\n2\n
Two details in that hardened command explain common real-world container bugs. First, passing --mount-proc alongside --pid --fork instructs unshare to clone a Mount namespace and remount /proc for the new PID namespace; omitting it would leave ps -ef displaying every host daemon even though --pid was enabled. Second, --user --map-root-user demonstrates UID mapping (when invoked from an unprivileged host user, uid_map maps container UID 0 to that unprivileged host UID rather than host 0). Full container runtimes such as containerd and runc go two steps further by calling pivot_root() into a clean root filesystem image and mounting /sys/fs/cgroup read-only or inside a cgroup namespace so the container cannot tamper with its own parent cgroup files.
Why namespaces and cgroups alone do not stop container breakouts
Namespaces conceal objects and cgroups bound resource consumption, yet neither mechanism strips dangerous kernel privileges or blocks risky system calls. Because every container still funnels system calls into the exact same Linux kernel, a container running as unmapped UID 0 with default privileges remains one misconfiguration or kernel bug away from host compromise.
Closing that gap requires layering three additional kernel defenses on top of namespaces and cgroups.
First, Linux capabilities break monolithic root authority into dozens of discrete privileges tracked across each task's effective, permitted, inheritable, and bounding sets. A reverse proxy that only needs to bind TCP port 443 does not need full root powers; granting solely CAP_NET_BIND_SERVICE while dropping everything else eliminates entire classes of post-exploitation abuse. Conversely, launching a container with --privileged or granting CAP_SYS_ADMIN effectively hands the container keys to mount filesystems, manipulate kernel modules or BPF programs, and escape its mount namespace entirely. Similarly, leaving CAP_NET_RAW enabled lets a compromised container craft raw Ethernet frames to spoof ARP or sniff traffic on a shared container bridge.
Second, the container daemon and bind-mount boundary often undermines kernel isolation before an attacker even touches a syscall. On traditional setups, the Docker daemon runs as host root because it must create namespaces, configure virtual Ethernet pairs, and mount container layers. If an operator bind-mounts the Docker control socket (/var/run/docker.sock) inside a CI runner or monitoring container, any process in that container can instruct the daemon to launch a new privileged container mounting the host's / directory or sensitive application secrets like /var/app/tenant-secrets.json. Exposing the Docker REST API over an unauthenticated TCP socket introduces a parallel hazard: malicious pages visited in a developer's browser or SSRF payloads from another container can drive the daemon directly unless the socket is gated by mutual TLS client certificates or SSH forwarding. Running the daemon in Rootless mode (executing the daemon itself inside an unprivileged user namespace) shrinks the blast radius even if the daemon is compromised.
Third, Seccomp-BPF and Mandatory Access Control (MAC) shrink the shared kernel attack surface. Even an unprivileged process can reach hundreds of Linux syscalls, some of which expose rarely audited kernel parsers or hardware drivers. Container runtimes attach a default seccomp profile that denies dozens of high-risk syscalls (kexec_load, init_module, acct, ptrace, or risky clone flags) with EPERM. Meanwhile, MAC frameworks like SELinux (using Multi-Category Security labels per container) and AppArmor evaluate subject-to-object labels independently of standard UNIX DAC permissions, blocking access to sensitive host paths or /proc entries even if a namespace or mount check misfires.
Production tradeoffs, edge cases, and verification checklist
Running hardened containers in production forces deliberate engineering tradeoffs between strict isolation, CPU scheduling latency, and kernel compatibility. Teams that copy arbitrary cgroup numbers or disable security layers without understanding the underlying mechanics routinely trade one outage for another.
The multi-core CPU throttling trap
Setting cpu.max too aggressively on multi-threaded runtimes such as the JVM, Go, or Node.js creates severe tail-latency spikes even when average CPU utilization looks healthy. Suppose a Go service has cpu.max set to 100000 100000 (1.0 CPU core equivalent per 100ms period), yet runs on a 32-core host. Because Go initializes GOMAXPROCS from the host core count unless explicitly tuned (or configured via cgroup-aware tooling), 32 worker goroutines can execute concurrently across 32 host cores and burn the entire 100ms budget in just 3.1 milliseconds of wall-clock time. For the remaining 96.9 milliseconds of that period, the kernel freezes every thread in the container. Always align runtime thread pools with cgroup quotas and monitor nr_throttled and throttled_usec inside cpu.stat rather than relying solely on average CPU graphs.
User namespace tradeoffs and unprivileged attack surface
Enabling User namespaces protects the host filesystem if a container breaks out of its chroot, yet creates two operational realities. File ownership on shared persistent volumes must align with shifted UIDs (100000 instead of 0), which historically forced slow recursive chown operations at container start until kernel idmapped mounts (introduced in Linux 5.12+) solved the translation zero-copy in the VFS layer. Additionally, granting unprivileged tasks CAP_SYS_ADMIN inside a new User namespace exposes complex kernel network and filesystem configuration paths (such as nf_tables and overlayfs) to unprivileged local users. Several Linux distributions therefore restrict unprivileged user-namespace creation via AppArmor profiles or sysctl knobs so only trusted runtimes can invoke it.
Shared bridge networking and lateral movement
By default, containers attached to the same Docker bridge sit on a virtual Ethernet switch sharing a Layer 2 broadcast domain. Even with airtight PID and Mount namespaces, a compromised web container can scan and probe internal databases or admin endpoints on 172.17.0.0/16 unless traffic is segmented. Production architectures replace the default shared bridge with isolated user-defined networks, host firewall rules (nftables), or Kubernetes NetworkPolicy enforcement, ensuring each workload can reach only explicitly declared peer ports.
Operational verification checklist
Before promoting a container configuration or platform baseline to production, validate each layer against live kernel state rather than trusting YAML manifests alone:
| Isolation Layer | What to Verify | Inspection Command or Telemetry Signal |
|---|---|---|
| Namespaces | Container sees only its own PIDs, interfaces, and mount root | Run ps -ef and ip addr inside container; verify unique inodes in /proc/self/ns/ |
| Credentials & Userns | Container runs non-root or maps UID 0 to unprivileged host UID | Inspect /proc/<pid>/uid_map and Uid / CapEff lines in /proc/<pid>/status |
| cgroups v2 Limits | CPU, memory, swap, and PID ceilings are active and non-throttled | Read cpu.max, cpu.stat, memory.max, memory.pressure (PSI), and pids.max |
| Capabilities & Seccomp | CAP_SYS_ADMIN, CAP_NET_RAW, and risky syscalls are dropped |
Check NoNewPrivs: 1 and Seccomp: 2 in /proc/<pid>/status; audit CapBnd |
| Daemon & Network | No docker.sock mount; L2/L3 east-west container traffic segmented |
Inspect container mounts for host paths; verify firewall or NetworkPolicy drops |
When you treat a container not as a magic black box, but as an explicit composition of kernel namespaces, cgroups v2 budgets, mapped credentials, stripped capabilities, and seccomp filters, every midnight CPU freeze or isolation boundary failure becomes straightforward to diagnose and prevent before it reaches production.
References & Sources
Related Security Reads

Rate Limiting and Brute-Force Defense: Blocking Attackers, Not Users
Build multi-dimensional rate limiting with GCRA token buckets, trusted proxy parsing, and HTTP 429 cooldowns to block brute force without self-DoS.

TLS Handshake in HTTPS: How Browsers Negotiate Encrypted Web Connections
Explore how TLS 1.3 and 1.2 handshakes verify server identity, derive forward-secret AEAD keys, prevent downgrade attacks, and handle 0-RTT replay tradeoffs.

LLM Output Security: Preventing XSS and SQL Injection at Sink Boundaries
Treat LLM responses as untrusted input. See how prompt injection turns generated text into XSS or SQLi, and enforce context encoding and parameterized queries.

Software Bill of Materials (SBOM): Internals, Formats, and CVE Response
Learn how SBOMs map transitive dependencies via CycloneDX, SPDX, and PURLs, integrate with VEX and SLSA attestations, and cut CVE triage from hours to seconds.
Get new posts by email
No ads, no tracking. Just new posts, unsubscribe any time.
Comments
No comments yet.