In this lesson, you will learn how to stabilize your host system by imposing strict memory boundaries on isolated process groups using cgroup v2.
When you isolate a process within a namespace, you provide it with an illusion of independence, but the kernel’s underlying memory management remains shared. If a containerized application enters a memory leak or an unconstrained growth cycle, it can trigger the system-wide Out-Of-Memory (OOM) killer, potentially crashing critical host services. To prevent this, we utilize the memory controller within the cgroup v2 hierarchy to enforce hard and soft limits.
Hard vs. Soft Limits
- Hard Limits (
memory.max): This is the absolute ceiling. If a process group attempts to allocate memory beyond this threshold, the kernel will refuse the allocation and trigger an immediate reclaim process. If the memory cannot be reclaimed, the OOM killer will target a process within that specific cgroup, sparing the rest of the host. - Soft Limits (
memory.low/memory.high): These act as advisory boundaries. Whilememory.highacts as a throttling threshold that forces processes to perform direct memory reclamation when exceeded,memory.lowprovides a "guaranteed" protection level. It tells the kernel to avoid reclaiming memory from this specific group unless absolutely necessary, ensuring stability for high-priority background tasks.
Practical Implementation
To apply these limits, you interact directly with the cgroup filesystem. Assuming you have established a control group named web_app_group, you define the boundaries by writing to the corresponding control files:
# Set a hard limit of 512MB
echo 536870912 > /sys/fs/cgroup/web_app_group/memory.max
# Set a high-pressure threshold at 400MB to trigger early reclamation
echo 419430400 > /sys/fs/cgroup/web_app_group/memory.high
By configuring these parameters, you shift the responsibility of memory pressure from the host kernel’s global state to the individual process group. This granular control allows you to "fence in" your workloads, ensuring that resource-hungry applications remain contained without compromising the integrity of the host OS or other co-located containers.
Key Takeaway: By defining memory.max and memory.high in cgroup v2, you transform memory management from a global competitive race into a predictable, isolated allocation model that protects the host from OOM-induced instability.