Q: Explain how Linux Namespaces and Cgroups work together to isolate and limit container resources. Why does removing a container process not delete the cgroup, and what happens if you reuse the cgroup name?
Namespaces and Cgroups are complementary isolation mechanisms:
🛠️ Production Runbook & Step-by-Step Resolution
Initial Diagnostics & Root Cause Analysis
Namespaces and Cgroups are complementary isolation mechanisms:
- Creates new namespaces for the process:
unshare(CLONE_NEWPID | CLONE_NEWNET | ...) - Assigns the process to a cgroup:
/sys/fs/cgroup/memory/docker/with/ memory.limit_in_bytes=512M - The container process thinks it's PID 1 (due to PID namespace) but the host sees it as PID 4567.
Remediation & Permanent Safeguards
Namespaces isolate *visibility* (PID namespace hides other processes, network namespace creates a separate NIC, filesystem namespace provides a chroot-like view). Cgroups enforce *resource limits* (CPU shares, memory cap, I/O bandwidth, etc.). When a container starts, the container runtime (Docker/containerd): When the container process terminates, the cgroup persists because cgroups are kernel-managed resource accounting structures separate from process lifecycles. The kernel keeps tracking memory usage, I/O metrics, etc., even if the process exits. This allows inspecting historical resource consumption after a crash. Reusing the same cgroup name: If you spin up a new container and reuse the same cgroup path without cleaning up the old one, the new process joins the cgroup with the old memory limit still in place and metrics still aggregating. This can cause unexpected behavior (e.g., the old limit prevents the new container from starting). Container runtimes always clean up cgroups (or create unique names with container IDs) to prevent this collision.
- Creates new namespaces for the process: unshare(CLONE_NEWPID | CLONE_NEWNET | ...)
- Assigns the process to a cgroup: /sys/fs/cgroup/memory/docker// with memory.limit_in_bytes=512M
- The container process thinks it's PID 1 (due to PID namespace) but the host sees it as PID 4567.