Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 18 of 8021. Container FundamentalsFree lesson

Managing Memory Allocation via Memory Cgroups

Learners will set memory thresholds and limits using Cgroups to prevent individual containers from exhausting host system RAM.

In this lesson, you will learn how to use Memory Cgroups to define hard boundaries on a container's RAM usage, ensuring your host system stays stable even if an application starts consuming excessive memory.

The Problem: The "Greedy" Container

In our previous lessons, we learned how namespaces isolate processes so they can't see each other. However, namespaces do not prevent a process from "stealing" resources. Without resource governance, a single containerized application could allocate all available physical RAM on your host. If that happens, the host kernel may trigger the OOM (Out of Memory) Killer, which could randomly terminate critical system processes—or even the host OS itself—to reclaim memory.

Controlling Memory with Cgroups

The memory controller in Linux Cgroups allows us to define strict limits on how much RAM a container can access. When you set a limit, the kernel keeps a running count of the memory used by all processes within that specific group. If a process inside the container tries to request memory that would push the total usage above your defined threshold, the kernel will deny the request or trigger an OOM event specifically for that container, keeping the rest of your system untouched.

In a container runtime like Docker, you apply these limits using flags that interface directly with the underlying Cgroup subsystems. For example:

docker run --memory="512m" nginx

In this command, you are instructing the Linux kernel to create a Cgroup for the Nginx container with a hard limit of 512MB of RAM. If Nginx attempts to use 513MB, the Cgroup controller steps in to stop it.

Why This Matters

By managing memory at the container level, you create "noisy neighbor" protection. In a Kubernetes or CI/CD environment, this is essential. You want to ensure that a heavy build job or a memory-leaking microservice stays within its designated "sandbox," leaving enough system memory for the host to manage networking, storage, and other healthy containers. You are moving from a world where processes compete for resources to a world where they operate within clear, predefined envelopes.

Key Takeaway: Memory Cgroups act as a safety governor, enforcing hard RAM limits on containers to prevent runaway processes from crashing your host system.