In this lesson, you will learn how to bridge the gap between raw cgroup controllers and persistent service lifecycles by leveraging systemd as your resource orchestrator.
Bridging Cgroups and Service Units
While cgroup v2 provides the granular mechanisms for limiting CPU, memory, and device access, managing these manually via the /sys/fs/cgroup filesystem is fragile and non-persistent across reboots. systemd acts as the declarative manager for these primitives, allowing you to embed resource constraints directly into unit files. By doing this, you ensure that resource policies are coupled with the application’s lifecycle—meaning the limits exist exactly when the process exists and vanish when it stops.
Implementing Persistent Policies
To enforce resource limits, you specify directives within the [Service] section of a unit file. Because systemd understands the underlying cgroup hierarchies, it translates these directives into the appropriate hierarchy configuration automatically.
Consider a memory-intensive background worker that must never exceed 512MB of RAM. Instead of writing scripts to manage cgroups, you simply configure the service:
[Service]
ExecStart=/usr/bin/data-processor
MemoryMax=512M
CPUWeight=500
IOWeight=100
When you run systemctl start, systemd places the process in a dedicated cgroup slice, applying the MemoryMax constraint immediately. If the process exceeds this, the kernel—via the cgroup controller—will invoke the OOM killer or throttle the process according to your policy.
Why This Matters for Containerization
In our broader study of containerization primitives, this integration is vital. Containers are, fundamentally, processes confined by namespaces and cgroups. When you deploy a containerized application via systemd, you are using the same resource management infrastructure that powers the service manager itself. This provides a unified interface to audit resource consumption using systemd-cgtop or systemctl status, allowing you to monitor "Pressure Stall Information" (PSI) metrics directly tied to the service’s performance, ensuring your resource policies remain enforced throughout the entire runtime lifecycle of the application.
Key Takeaway: Systemd transforms raw cgroup primitives into persistent, declarative resource policies that are automatically governed as part of the service’s lifecycle.