By | June 3, 2025

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, vmstat
    • smem or ps_mem for detailed per-process memory
    • dstat -m or glances for live system monitoring
  • Set up alerts using:
    • prometheus + grafana
    • monit
    • zabbix or nagios

2. Configure Swap Space

  • Add swap space if none or too little is configured: bashCopyEditsudo fallocate -l 4G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile
  • Make it permanent: Add to /etc/fstab bashCopyEdit/swapfile none swap sw 0 0
  • Tweak swappiness: bashCopyEditsudo sysctl vm.swappiness=10 Add to /etc/sysctl.conf for persistence: iniCopyEditvm.swappiness = 10

3. Use Memory Limits and Cgroups (For Services/Containers)

  • With systemd services: iniCopyEdit[Service] MemoryMax=512M Then reload: bashCopyEditsudo systemctl daemon-reexec
  • For containers (e.g., Docker): bashCopyEditdocker run -m 512m --memory-swap 1g your_image
  • With cgroups manually: bashCopyEditecho 512M > /sys/fs/cgroup/memory/mygroup/memory.limit_in_bytes

4. Avoid Memory Leaks in Applications

  • Profile apps using:
    • valgrind, massif
    • perf
    • Language-specific tools (e.g., gperftools, objgraph for 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.