The Linux OOM (Out of Memory) killer terminates processes when the system runs out of memory. This guide explains how to diagnose OOM events and prevent them.
Check for OOM Events
$dmesg | grep -i "oom|killed process|out of memory"[123456.789] Out of memory: Kill process 12345 (php-fpm) score 892 or sacrifice child
[123456.790] Killed process 12345 (php-fpm) total-vm:456789kB, anon-rss:123456kB$journalctl -k | grep -i oom | tail -20Check Current Memory Usage
$free -h total used free shared buff/cache available
Mem: 1.9Gi 1.8Gi 45Mi 12Mi 234Mi 123Mi
Swap: 0B 0B 0B$ps aux --sort=-%mem | head -10Immediate Fixes
Add Swap Space
$fallocate -l 2G /swapfile$chmod 600 /swapfile$mkswap /swapfile$swapon /swapfile$echo '/swapfile none swap sw 0 0' >> /etc/fstabRestart Memory-Leaking Services
If a specific service is leaking memory, restart it:
$systemctl restart php8.1-fpm$systemctl restart nginxTune PHP-FPM Memory Usage
Edit /etc/php/8.1/fpm/pool.d/www.conf:
pm = dynamic
pm.max_children = 10
pm.start_servers = 3
pm.min_spare_servers = 2
pm.max_spare_servers = 5
pm.max_requests = 500Calculate the appropriate pm.max_children:
$# Check average PHP-FPM process memory usage$ps aux | grep php-fpm | awk '{print $6}' | sort -n | tail -5# If average is ~50 MB and you have 2 GB RAM with 512 MB for OS/MySQL:
# Available for PHP: 1.5 GB = 1500 MB
# max_children = 1500 / 50 = 30Protect Critical Processes from OOM Killer
$# Protect MySQL from being killed$echo -17 > /proc/$(pgrep mysqld)/oom_adj$$# Or use oom_score_adj (modern kernels)$echo -1000 > /proc/$(pgrep mysqld)/oom_score_adj[!TIP] If OOM events are frequent, the server needs more RAM. Consider upgrading to a larger plan or optimising your application's memory usage.
