How To Avoid Oom Killer Linux
The OOM Killer (Out of Memory Killer) in Linux is a last-resort mechanism that kills processes when the system runs out of memory. To avoid triggering the OOM Killer, you need to manage memory proactively. Here’s a structured guide:
🛡️ How to Avoid the OOM Killer in Linux
1. Monitor and Manage Memory Usage
- Use tools like:
htop,top,free -m,vmstatsmemorps_memfor detailed per-process memorydstat -morglancesfor live system monitoring
- Set up alerts using:
prometheus + grafanamonitzabbixornagios
2. Configure Swap Space
- Add swap space if none or too little is configured: bashCopyEdit
sudo fallocate -l 4G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile - Make it permanent: Add to
/etc/fstabbashCopyEdit/swapfile none swap sw 0 0 - Tweak swappiness: bashCopyEdit
sudo sysctl vm.swappiness=10Add to/etc/sysctl.conffor persistence: iniCopyEditvm.swappiness = 10
3. Use Memory Limits and Cgroups (For Services/Containers)
- With
systemdservices: iniCopyEdit[Service] MemoryMax=512MThen reload: bashCopyEditsudo systemctl daemon-reexec - For containers (e.g., Docker): bashCopyEdit
docker run -m 512m --memory-swap 1g your_image - With
cgroupsmanually: bashCopyEditecho 512M > /sys/fs/cgroup/memory/mygroup/memory.limit_in_bytes
4. Avoid Memory Leaks in Applications
- Profile apps using:
valgrind,massifperf- Language-specific tools (e.g.,
gperftools,objgraphfor Python)
- Restart services periodically (crontab or systemd timers) if leaks are known and unpatched.
5. Disable the OOM Killer for Critical Processes (With Caution)
You can “protect” a process from the OOM Killer:
bashCopyEditecho -17 > /proc/<pid>/oom_score_adj
Or disable for specific systemd units:
iniCopyEdit[Service]
OOMScoreAdjust=-1000
⚠️ Caution: This could cause system lockup if no killable process remains.
6. Use EarlyOOM (Optional)
Install earlyoom to handle memory pressure before OOM Killer kicks in:
bashCopyEditsudo apt install earlyoom
It kills less-critical processes earlier, avoiding system freeze.
