Understanding OOM
When Linux runs out of memory, the OOM Killer terminates processes. Logs show:
sudo dmesg | grep -i "out of memory"
sudo journalctl | grep -i "oom"
sudo grep -i "killed process" /var/log/syslog
Check Current Memory Status
free -h
cat /proc/meminfo
vmstat -s
Find Memory Hogs
ps aux --sort=-%mem | head -15
smem -r -k | head -20
Emergency Fixes
1. Add Swap Space
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo "/swapfile none swap sw 0 0" | sudo tee -a /etc/fstab
2. Kill Memory-Hungry Process
ps aux --sort=-%mem | head -2 | tail -1 | awk '{print $2}'
sudo kill -9 PID
3. Clear Caches
sudo sync && echo 3 > /proc/sys/vm/drop_caches
Preventive Configuration
Systemd Memory Limits
sudo systemctl set-property service-name MemoryMax=512M
sudo systemctl daemon-reload
OOM Behavior
sysctl -w vm.overcommit_memory=1
sysctl -w vm.overcommit_ratio=90
echo "vm.overcommit_memory=1" >> /etc/sysctl.conf
echo "vm.overcommit_ratio=90" >> /etc/sysctl.conf
Application Limits
- PHP: reduce memory_limit in php.ini
- MySQL: reduce innodb_buffer_pool_size
- Apache: reduce MaxRequestWorkers
- Node.js: use --max-old-space-size
💡 Long-term fix: upgrade VPS RAM if usage is consistently high.