Namespaces & Cgroups

Linux container primitives: PID, network, mount, user namespaces for isolation

published: reading time: 21 min read author: Geek Workbench
Quick Summary

Linux container primitives: PID, network, mount, user namespaces for isolation

Namespaces & Cgroups

Linux containers share the host kernel, but they do not have to share every view of the system or every resource budget. Namespaces change what a process can see. Cgroups account for and limit how much CPU, memory, and I/O a group of processes can use. Both are useful isolation mechanisms, but neither is a complete security boundary on its own.

Namespaces give processes different views of selected kernel resources. A process can be PID 1 in its PID namespace and have a different PID on the host. A network namespace has its own network interfaces, routes, and port space. What a namespace hides depends on the resource and the process’s privileges; it is not a blanket access-control rule.

Cgroups (control groups) group processes so the kernel can account for their resource use and, when configured, enforce limits. A cgroup does not automatically cap a workload: the relevant controller must be available and a limit must be set.

Container runtimes such as Docker combine namespaces and cgroups with other controls. Capabilities, user-namespace mappings, seccomp, Linux security modules, device access, and runtime configuration all affect the result. Containers still share the host kernel, so use a virtual machine or another stronger isolation boundary when the threat model calls for one.

Introduction

Linux namespaces and cgroups let processes share one kernel while receiving different resource views and budgets. A virtual machine runs a guest operating system on virtual hardware; a container uses the host kernel. That difference matters when choosing an isolation boundary for untrusted workloads.

Each namespace type changes the view of a particular resource, such as process IDs, network interfaces, or mount points. The view can still be affected by shared namespaces, privileges, and other kernel interfaces.

Cgroups form a hierarchy. A child remains subject to limits imposed by its ancestors, while its own limits can further restrict the processes placed in it. The hierarchy accounts for usage as well as enforcing configured limits.

When to use these details

These details are useful when a process cannot see an expected PID, a service has no network route, or a workload is being throttled. They also help when reviewing how a container runtime applies resource limits.

Namespaces and cgroups are common parts of container isolation on shared hosts. They should be reviewed alongside the runtime’s capabilities, user mappings, seccomp profile, device policy, and mandatory access-control policy.

For workloads you do not trust, remember that containers share the host kernel. A kernel vulnerability or a permissive runtime configuration can cross the intended boundary. A virtual machine provides a separate guest kernel and is often a better fit when that extra separation matters.

How namespaces and cgroups fit together

graph TD
    subgraph Host System
        H[Host Processes] --> HCG[Host Cgroup]
        HCG --> HCGOV[CPU, Memory, IO Controllers]
    end

    subgraph Container A
        CA[Container A Processes] --> ACG[Container A Cgroup]
        ACG --> ACGOV[CPU: 2 cores<br/>Memory: 4GB limit]
        ANP[Network NS] --> AIF[Isolated Net Interface]
        APID[PID NS] --> AP1[PID 1 inside container]
    end

    subgraph Container B
        CB[Container B Processes] --> BCG[Container B Cgroup]
        BCG --> BCGOV[CPU: 1 core<br/>Memory: 2GB limit]
        BNP[Network NS] --> BIF[Isolated Net Interface]
    end

    HCGOV --> ACGOV
    HCGOV --> BCGOV

    style Container A stroke:#00fff9
    style Container B stroke:#ff00ff

The diagram separates the two jobs: namespaces change selected resource views, while cgroups account for usage and enforce configured limits. The exact hierarchy and limits depend on the runtime and host configuration. Neither mechanism alone prevents a process with sufficient privileges from reaching host resources.

Core concepts

Namespace types

Linux provides several namespace types. Each applies to a particular set of kernel resources.

PID namespace: Gives processes a separate PID view. The first process in a new PID namespace is PID 1 there and handles orphaned child processes. A process in a parent namespace can see processes in descendant PID namespaces, but a process in a child namespace cannot see processes in its parent namespace.

Network namespace: Has its own network devices, routes, firewall rules, and port-number space. A service can bind to the same port in two separate network namespaces because each namespace has its own sockets and interfaces.

Mount namespace: Gives processes a separate set of mount points. A container runtime can combine a mount namespace with a root filesystem setup such as pivot_root; chroot alone is not a substitute for container isolation. Propagation settings also determine whether mount changes are shared.

User namespace: Maps user and group IDs and scopes capabilities. A process can have UID 0 inside a user namespace while mapping to an unprivileged UID on the host. This reduces the authority of that process outside the namespace, but does not make every operation safe or replace other security controls.

UTS namespace: Gives processes a separate hostname and NIS domain name.

IPC namespace: Isolates System V IPC objects and POSIX message queues from processes in other IPC namespaces.

Cgroup controllers and version-specific files

Cgroup v1 gives controllers separate hierarchies, so a process can have different paths for CPU and memory. Cgroup v2 uses one hierarchy. The control-file names changed between versions; do not assume that a v1 path or file exists on a v2 host.

The CPU controller accounts for CPU time and can apply a quota. The memory controller tracks memory and can enforce a limit. The I/O controller can set relative weights or bandwidth limits, and the PIDs controller can cap the number of processes. A controller may be unavailable or not enabled for a particular cgroup.

First identify the hierarchy and the process’s cgroup path:

findmnt -rn -t cgroup,cgroup2 -o TARGET,FSTYPE,OPTIONS
cat /proc/self/cgroup

On a legacy cgroup v1 host, controller mount points and process paths vary. This read-only example discovers the CPU and memory mounts and then reads the v1 quota and memory files for the current process. It assumes the mount root is /; check the findmnt output if your host uses a different root.

cpu_mount=$(findmnt -rn -t cgroup -o TARGET,OPTIONS | awk '$0 ~ /(^|,)cpu(,|$)/ {print $1; exit}')
memory_mount=$(findmnt -rn -t cgroup -o TARGET,OPTIONS | awk '$0 ~ /(^|,)memory(,|$)/ {print $1; exit}')
cpu_path=$(awk -F: '$2 ~ /(^|,)cpu(,|$)/ {print $3; exit}' /proc/self/cgroup)
memory_path=$(awk -F: '$2 ~ /(^|,)memory(,|$)/ {print $3; exit}' /proc/self/cgroup)

cat "${cpu_mount}${cpu_path}/cpu.cfs_quota_us"
cat "${cpu_mount}${cpu_path}/cpu.cfs_period_us"
cat "${memory_mount}${memory_path}/memory.limit_in_bytes"
cat "${memory_mount}${memory_path}/memory.usage_in_bytes"

On Ubuntu 26.04 LTS, the systemd hierarchy uses cgroup v2. For example, these commands read the CPU and memory files for system.slice:

systemd_path=$(systemctl show --property=ControlGroup --value system.slice)
cat "/sys/fs/cgroup${systemd_path}/cgroup.controllers"
cat "/sys/fs/cgroup${systemd_path}/cpu.max"
cat "/sys/fs/cgroup${systemd_path}/memory.max"
cat "/sys/fs/cgroup${systemd_path}/memory.current"

For a service or container, use its path from systemctl show ... ControlGroup or /proc/PID/cgroup instead of system.slice. cpu.max contains a quota and period; memory.max is the hard memory limit (max means no limit at that cgroup). These files are kernel interfaces, so read them before changing resource settings.

Production failure scenarios

Scenario: A container reaches its memory limit

Problem: A container reaches its memory limit and a process is killed by the cgroup OOM handler.

Symptoms: The process exits unexpectedly, a workload restarts, or the kernel log records an OOM event. The exact behavior depends on the cgroup and runtime configuration.

Mitigation: Check the cgroup’s memory usage and event counters, then compare them with the workload’s expected peak. In Kubernetes, a memory request is used for scheduling; a memory limit is the ceiling. A request does not reserve physical memory for the container.

# Check the container's recorded exit state
docker inspect --format '{{.State.OOMKilled}} {{.State.ExitCode}}' CONTAINER_ID

# View OOM events in journal
journalctl -k | grep -i memory

# On cgroup v2, inspect memory event counters at the container's cgroup path
cat /sys/fs/cgroup/CONTAINER_CGROUP_PATH/memory.events

The cgroup path depends on the runtime and its cgroup driver. Use docker inspect and /proc/PID/cgroup to find the process path, then follow the version-specific commands above.

Scenario: CPU throttling raises latency

Problem: A configured CPU quota can throttle a workload before it finishes its work for the current scheduling period.

Symptoms: cpu.stat shows throttling while request latency rises under load. A low average CPU reading does not rule out quota throttling.

Mitigation: Compare the quota with the workload’s burst pattern. In Kubernetes, CPU requests affect scheduling and relative allocation; CPU limits cap usage. Tune limits from measurements rather than removing them by default.

# Check the host's cgroup version before choosing a cpu.stat path
docker info --format 'cgroup={{.CgroupVersion}} driver={{.CgroupDriver}}'
# Read cpu.stat from the container's cgroup path; see the v1/v2 examples above
cat /sys/fs/cgroup/CONTAINER_CGROUP_PATH/cpu.stat

Scenario: An unexpected host-level privilege

Problem: A container has more host access than its workload needs. A namespace setting alone does not reveal every source of privilege.

Symptoms: The container runs as privileged, has broad capabilities, maps container root directly to host root, or shares a host namespace or sensitive host path.

Mitigation: Inspect the container configuration and the process’s user mapping. Drop capabilities the workload does not need, avoid --privileged, and review bind mounts and namespace modes. User namespaces can reduce host authority, but they do not replace the other checks.

# Review privileged mode, capability overrides, and namespace modes
docker inspect --format 'privileged={{.HostConfig.Privileged}} cap_add={{json .HostConfig.CapAdd}} cap_drop={{json .HostConfig.CapDrop}} pid_mode={{.HostConfig.PidMode}} network_mode={{.HostConfig.NetworkMode}}' CONTAINER_ID

# Inside the container, check the identity and UID mapping
docker exec CONTAINER_ID sh -c 'id; cat /proc/self/uid_map; grep -E "^Cap(Eff|Prm):" /proc/self/status'

Trade-offs

Namespace Type Isolation Provided Performance Impact Configuration Complexity
PID Process ID numbers Negligible Low
Network Interfaces, routing, ports Low to medium Medium
Mount Filesystem mounts Negligible Medium
User UID/GID mapping Negligible Medium
UTS Hostname/domain None Low
IPC Message queues, shared memory Negligible Low
Resource Control Mechanism Suitable For Limitations
CPU limit (CFS) Time quota per period Batch workloads Can cause throttling
CPU limit (cpuset) CPU affinity Latency critical Reduces flexibility
Memory limit Hard cap Multi-tenant Can trigger OOM
Memory swap Swap usage Memory pressure Depends on host swap
I/O weight Relative priority Competing workloads Shared disk required
I/O throttle Absolute bandwidth Guaranteed QoS Complex tuning
Runtime Namespace support Cgroup support
Docker Linux namespaces v1 or v2, depending on engine version and host
containerd Linux namespaces v1 or v2, depending on runtime version and host
CRI-O Linux namespaces v1 or v2, depending on runtime version and host
Podman Linux namespaces v1 or v2, depending on version and host
runc Linux namespaces v1 or v2, depending on version and host

Check the runtime and host rather than inferring the cgroup version from the product name. On Docker, docker info reports the active cgroup version and driver.

A safe local lab

Create a temporary PID namespace

unshare --user --map-root-user --pid --fork --mount-proc \
  sh -c 'printf "PID in new namespace: "; echo "$$"; ps -o pid,comm'

This starts a short-lived shell in new user and PID namespaces; it does not change host network settings or write cgroup controls. User-namespace creation may be disabled by the host. If unshare reports that the operation is not permitted, do not retry with broader privileges on a production machine.

Inspect namespace IDs

pid=$$
printf 'Current shell namespaces:\n'
ls -l "/proc/${pid}/ns"
printf '\nHost init PID namespace:\n'
readlink /proc/1/ns/pid

Apply temporary cgroup limits with systemd

On a systemd host with a delegated user manager and cgroup v2, this starts a one-minute user scope with a 50% CPU quota and a 256 MiB memory ceiling. Run the first command in one terminal and inspect it from another before it exits:

systemd-run --user --scope --unit=cgroup-lab \
  --property=CPUQuota=50% --property=MemoryMax=256M sleep 60
group=$(systemctl --user show --property=ControlGroup --value cgroup-lab.scope)
cat "/sys/fs/cgroup${group}/cpu.max"
cat "/sys/fs/cgroup${group}/memory.max"

The scope disappears when sleep exits. If the user manager does not allow these resource controls, stop here and use a disposable VM where you can safely inspect the host configuration.

Observability checklist

  • Use docker stats or your orchestrator’s metrics to compare a container’s CPU and memory use with its configured limits.
  • Read cpu.stat, memory.current / memory.events, or the corresponding v1 files from the process’s actual cgroup path. File names differ between v1 and v2.
  • Check pids.current against pids.max when process creation fails.
  • Correlate cgroup events with application logs and host kernel logs; a single metric rarely explains an incident by itself.
  • Review namespace modes, capabilities, user mappings, seccomp, and mounted host paths during a configuration audit. These settings show intended isolation, not proof that an escape is impossible.

Security notes

Capabilities: Give the workload only the capabilities it needs. Runtime defaults vary, so inspect the actual configuration and drop unnecessary capabilities.

No new privileges: The no-new-privileges setting prevents a process from gaining privileges through setuid or file-capability execution.

User namespace remapping: Map container IDs to unprivileged host IDs where the runtime and workload support it. A UID of 0 inside the container does not by itself tell you the host UID.

Seccomp: Restrict system calls the workload does not need. Review the profile actually applied by the runtime instead of relying on a fixed syscall count, which can change between releases.

Check host-level privilege: On the host, inspect the runtime configuration. Inside the container, compare its UID mapping and effective capabilities. UID 0 in a user namespace is not the same as host UID 0, and --privileged or broad host mounts can still grant substantial access.

# Kubernetes security context
securityContext:
  allowPrivilegeEscalation: false
  readOnlyRootFilesystem: true
  runAsNonRoot: true
  capabilities:
    drop:
      - ALL
    add:
      - NET_BIND_SERVICE

Common pitfalls

Treating container root as host root, or assuming it is harmless: Check user-namespace mappings and effective capabilities. A read-only root filesystem and a smaller capability set can reduce the impact of a compromise.

Leaving process counts unbounded: A PIDs limit can make fork() or clone() fail once the limit is reached. Set a limit that fits the workload and monitor it; an unset limit does not protect the host from a process storm.

Using host networking without a reason: --network=host shares the host network namespace, including its port space. It changes the isolation and exposure of the service; assess that trade-off before using it.

Sharing namespaces without accounting for the coupling: Containers that share a PID or network namespace can interact through that shared view. Decide which namespaces a pod or container group needs to share, then limit privileges within them.

Monitoring the wrong cgroup files: Confirm whether the host uses v1 or v2 and resolve the process’s cgroup path before reading controller files.

Quick recap

  • Namespaces change selected resource views for a process.
  • Cgroups account for resource use and enforce configured limits.
  • Neither one alone is a complete container security boundary.
  • PID namespaces provide isolated process ID spaces.
  • Network namespaces give containers independent network stacks.
  • Mount namespaces isolate filesystem views.
  • User namespaces map UIDs/GIDs between container and host.
  • CPU and memory controller files differ between cgroup v1 and v2.
  • A memory limit can lead to reclaim and, if the workload cannot stay below the limit, an OOM event.
  • Container runtimes create and manage namespaces automatically.
  • Container security also depends on capabilities, user mappings, seccomp, device policy, mounts, and runtime settings.
  • Monitor the cgroup files for the active version and the path assigned to the workload.

Interview questions

1. What is the difference between a namespace and a cgroup?

A namespace changes a process's view of a resource, such as its PID list or network stack. A cgroup accounts for processes and can enforce configured resource limits. Neither one alone controls every form of host access, so container security also depends on privileges and runtime settings.

2. How do PID namespaces work and why do they matter for containers?

A PID namespace gives processes their own PID view. Its first process is PID 1 and must handle orphaned children. Processes in a parent PID namespace can see processes in descendant namespaces; processes in a child namespace cannot see processes in the parent. Signal permissions still apply.

3. What happens when a container exceeds its memory limit?

The kernel first tries to reclaim memory. If usage cannot be brought under the configured limit, an out-of-memory event may follow and a process may be killed. Check the cgroup's memory event counters and runtime state to see what happened; a limit does not guarantee that the whole container restarts.

4. How do user namespaces improve container security?

A user namespace maps user and group IDs and scopes capabilities. A process can have UID 0 inside it while mapping to an unprivileged UID on the host. That reduces the process's authority outside the namespace, but it does not guarantee safety if another vulnerability or excessive privilege is present.

5. What is CPU throttling and how does it affect containerized applications?

A CPU quota caps the time a cgroup can run during each scheduling period. Once it uses that budget, the kernel throttles its tasks until the next period. This can increase tail latency under bursts. In Kubernetes, a CPU request affects scheduling; it does not replace a CPU limit.

6. How do parent cgroups affect their children?

Cgroups form a hierarchy, and a child remains subject to constraints imposed by its ancestors. The child does not automatically receive a fixed share of the parent's limit: siblings can use available capacity unless separate child limits or weights are configured. Paths and controller files also differ between cgroup v1 and v2.

7. How do cgroup v1 and v2 differ?

Cgroup v1 gives controllers separate hierarchies, so one process can have different CPU and memory paths. Cgroup v2 uses a unified hierarchy. The file names differ too: v1 uses files such as `cpu.cfs_quota_us` and `memory.limit_in_bytes`; v2 uses `cpu.max` and `memory.max`. Check for `/sys/fs/cgroup/cgroup.controllers` and inspect `/proc/PID/cgroup` to identify the active layout and path.

8. How does rootless container mode work?

Rootless runtimes let a non-root host user manage containers without giving the runtime full host-root authority. User namespaces can map container UID 0 to an unprivileged host ID. Some operations remain unavailable or need extra setup, such as access to host devices or certain network and storage features. The exact limits depend on the runtime and host.

9. What should you inspect when reviewing namespace isolation?

There is no single command that proves a container cannot escape. Start by reviewing its configured PID, network, and user namespace modes; capabilities; seccomp profile; device policy; and host mounts. Compare namespace IDs from `/proc/self/ns` inside and outside the container when you need to confirm whether a namespace is shared. Treat these checks as configuration evidence, not a security proof.

10. How does a container's kernel boundary differ from a virtual machine's?

Containers use the host kernel, while a virtual machine runs a guest kernel. A namespace boundary failure does not automatically grant host root, but a kernel flaw or an overly privileged runtime can expose host resources. A VM adds another isolation layer, though it is not an absolute guarantee either. Choose the boundary based on the workload and threat model.

11. How does the PIDs controller limit process creation?

When `pids.current` reaches `pids.max`, new `fork()` or `clone()` calls can fail with `EAGAIN`. The limit is not necessarily set by default, so check the runtime configuration and the cgroup files. A configured per-container limit can contain a process storm; without one, processes may use the host's available PID capacity.

12. How do cgroups control swap usage?

Swap controls are version-specific. Cgroup v1 has files such as `memory.memsw.limit_in_bytes` when swap accounting is enabled; cgroup v2 uses `memory.swap.max`. A swap limit does not replace the memory limit, and the default depends on the host and runtime. Swapping can increase latency, so inspect both memory and swap usage before changing either limit.

13. How do cgroups control block I/O?

The names and behavior depend on the cgroup version and storage stack. Cgroup v2 uses `io.weight` for relative weight and `io.max` for per-device limits. Cgroup v1 uses files under its `blkio` controller. A weight is not a fixed bandwidth guarantee, and actual I/O control depends on device and kernel support.

14. When are a container's namespaces released?

A namespace remains while a process or another reference holds it. Container runtimes normally release their references during cleanup, after the workload exits. Host networking explicitly shares the host network namespace. Kubernetes containers in a pod share the network namespace; PID sharing is configurable, and mount namespaces are not all shared automatically.

15. What does a UTS namespace isolate?

A UTS namespace gives its processes a separate hostname and NIS domain name. `unshare --uts` can create one when the caller has the required privilege in the relevant user namespace. Container runtimes commonly use this so a container can have its own hostname.

16. How do cgroup real-time CPU controls differ from regular quotas?

`cpu.rt_runtime_us` and `cpu.rt_period_us` are legacy cgroup v1 controls for real-time scheduling bandwidth. They are not the same as the regular CPU quota, and availability depends on kernel configuration. Cgroup v2 does not expose the same controller files, so check the kernel and runtime documentation before relying on real-time group controls.

17. What does freezing a cgroup do?

Cgroup v1 has a freezer controller; cgroup v2 exposes `cgroup.freeze` and `cgroup.events`. Freezing stops tasks in the cgroup but does not create an application checkpoint. Runtimes may use cgroup freezing to implement pause behavior. Do not assume that a frozen workload is ready for checkpoint or restart.

18. What access does `--privileged` grant?

`--privileged` grants a container broad capabilities and device access and relaxes other confinement, depending on the runtime. It is a high-risk setting, but it does not literally turn every container process into host root in every configuration. Inspect the user mapping, capabilities, devices, seccomp, and security-module profile. Drop capabilities the workload does not need.

19. How do serverless platforms use namespaces and cgroups?

Serverless platforms use containers, sandboxes, or other runtime mechanisms, but the isolation unit varies. A platform may reuse an environment across invocations or create a fresh one; do not assume there is one namespace or cgroup per function call. Check the platform's security model and lifecycle documentation for the actual boundary.

20. How are device access rules affected by cgroup version?

Cgroup v1 has a `devices` controller with allow and deny rules. Cgroup v2 does not expose the same devices-controller files, so device restrictions depend on the runtime and its host-kernel mechanisms. A missing `/dev` node is not the only control to review; check device access, capabilities, mounts, and the runtime's device policy together.

Further reading

Conclusion

Namespaces change what a process can see. Cgroups account for its resource use and enforce configured limits. Containers combine these mechanisms with other controls, but they still share the host kernel. When debugging a workload, check the active cgroup version, the process’s cgroup path, and the privileges the runtime gave it. Those details usually explain more than the word “container” does by itself.

Category

Related Posts

ASLR & Stack Protection

Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.

#operating-systems #aslr-stack-protection #computer-science

Assembly Language Basics: Writing Code the CPU Understands

Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.

#operating-systems #assembly-language-basics #computer-science

Boolean Logic & Gates

Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.

#operating-systems #boolean-logic-gates #computer-science