Linux cgroups: Limiting Process Resources Without the Pain

작성자

카테고리:

← 피드로
DEV Community · Schiff Heimlich · 2026-07-21 개발(SW)
Cover image for Linux cgroups: Limiting Process Resources Without the Pain

Schiff Heimlich

Linux cgroups: Limiting Process Resources Without the Pain

Let me share something I ran into last week that might save you a headache.

Had a script that was eating too much memory and killing adjacent services. The fix was simpler than I expected — systemd-run.

The Quick Fix

Instead of chasing down every poorly-written script and adding manual resource limits, you can just run the command with resource constraints upfront:

systemd-run --scope -p MemoryLimit=256M your-script.sh

Enter fullscreen mode Exit fullscreen mode

That’s it. The script gets its own scope with a 256MB memory cap. When it tries to allocate more, the OOM killer handles it gracefully instead of taking down the whole machine.

Why This Is Handy

The thing I like about systemd-run is that you don’t need to edit service files or reboot. It’s just a wrapper around the cgroups interface that systemd already manages.

If you want persistent limits — like for a service that should always have constraints — you edit the unit file:

[Service]
MemoryMax=512M
CPUQuota=50%

Enter fullscreen mode Exit fullscreen mode

A Couple of Flags Worth Knowing

MemoryHigh — this is the threshold where the kernel starts reclaiming memory aggressively. Useful if you want to warn before hitting the hard limit.

CPUQuota — takes a percentage. CPUQuota=50% means the service never gets more than half a CPU core, even if idle.

The cgroupfs Path (If You Need It)

For debugging, you can see what’s actually happening:

cat /sys/fs/cgroup/systemd/system.slice/your-service.scope/memory.max

Enter fullscreen mode Exit fullscreen mode

Each scope gets its own cgroup. You can read the limits, see current usage, and poke around without touching anything.

When I Reach for This

  • Scripts that call out to third-party binaries I don’t trust
  • One-off batch jobs that might go sideways
  • Isolating services on shared homelab hardware
  • Testing how software behaves under memory pressure

It’s not a silver bullet, but it’s one of those tools that’s cleaner than the alternatives I used to use (ulimit, nice, cgroups manually via /sys/fs/cgroup/).

Give systemd-run a shot next time you need to contain something. The manual pages are actually decent on this one.

Image: cgroups provide a hierarchical structure for resource control on Linux

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다