Why Does My VPS Keep Crashing? Memory Issues & Monitoring Solutions
Hey there! Mohamed here. This is one of the most common yet frustrating issues VPS owners face. A crashing server usually points to one primary culprit: running out of memory (RAM). The system's OOM (Out Of Memory) killer is likely being triggered to prevent a complete system freeze, sacrificing processes to keep the kernel alive.
Let's break down the why and how to fix it.
1. Check Your Memory Usage & Swap
First, connect via SSH and run these commands to see your real-time memory usage:
# Check memory and swap usage free -h # Check for the most recent OOM killer activity (if any) dmesg -T | grep -i "killed process" # Check running processes sorted by memory usage ps aux --sort=-%mem | head -n 10
- If your
freememory is consistently near zero, you're hitting the limit. - If you have little to no
swapspace configured, the system has no safety buffer and will crash sooner.
2. Configure Swap Space (If Missing)
Swap acts as emergency RAM on your disk. If you don't have any, let's add some (example for a 2GB swap file):
# Create a swap file sudo fallocate -l 2G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile # Make it permanent by adding to /etc/fstab echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Warning: Swap is much slower than RAM. It's a temporary fix, not a solution.
3. Identify & Optimize the Memory Hogs
Use htop or top to see which processes are using the most memory. Common culprits are:
- Database servers (MySQL/PostgreSQL): Poorly optimized queries or inadequate caching.
- Web servers (Apache/Nginx): Too many worker processes/threads.
- PHP-FPM: High
pm.max_childrensettings.
For a web server, consider reducing worker processes and enabling more aggressive caching.
4. Implement Basic Monitoring
You need to know when your memory is getting high before it crashes. Set up a simple monitor:
# Install a simple monitoring tool like htop sudo apt update && sudo apt install htop # Run htop to see live stats htop
For long-term monitoring, consider tools like Netdata (lightweight) or Prometheus+Grafana (more advanced).
Next Steps
If you're consistently running out of memory on a VPS, the ultimate solution is often to scale up your RAM. Optimizing software can only get you so far. Consider upgrading your VPS plan or optimizing your application's memory footprint.
Need help digging into the specific processes causing your crashes? Reach out for a performance audit. We can identify the root cause and get your server stable.