In this lesson, you will learn how to use Control Groups (cgroups) to act as a "resource traffic cop," ensuring that your containers play nice with the host system.
Understanding the "Noisy Neighbor" Problem
When you run multiple containers on a single host, they all share the same physical CPU, memory, and disk I/O. Without intervention, a single runaway application—perhaps a memory-leaking script or a process stuck in an infinite loop—could consume every available resource, causing the host machine and all other containers to crash. This is known as the "noisy neighbor" problem.
Managing Resources with cgroups
Control Groups, or cgroups, are a Linux kernel feature that Docker uses to group processes together and enforce usage boundaries. Instead of letting a container take whatever it wants, you can define "budgets" for your containers.
Enforcing Limits in Docker
When you start a container, you can pass flags to the Docker engine to set these boundaries. For example, if you want to ensure a container never uses more than 512MB of RAM and stays under 50% of a single CPU core, you would run:
docker run -d \
--memory="512m" \
--cpus="0.5" \
my-app-image
Here is what is happening under the hood:
- Memory: Docker creates a memory cgroup for the container. Once the process hits 512MB, the kernel prevents further allocation. If the application continues to demand more, the kernel may trigger an "Out of Memory" (OOM) kill, shutting down the container to save the host.
- CPU: The CPU cgroup uses a scheduler to ensure the container only receives the percentage of CPU cycles you authorized, preventing it from starving other processes.
- I/O: You can similarly restrict how much data a container can read from or write to the disk (using
--device-write-bps), preventing one container from saturating the storage bandwidth.
By implementing these limits, you transform your host from a collection of unpredictable processes into a stable, governed environment where every container operates within its assigned lane.
Key Takeaway: Control Groups (cgroups) are the fundamental mechanism that allows you to set hard limits on memory, CPU, and I/O, protecting your host and other containers from resource starvation.