Your applications are crashing unexpectedly. Services randomly stop. You see "Out of memory" or "Cannot allocate memory" errors in your logs. Your VPS is running out of RAM.
This guide will help you diagnose what's consuming memory, fix the immediate issue, and implement permanent solutions to prevent OOM (Out of Memory) errors.
Diagnose: Is It Really a Memory Issue?
Check current memory usage:
# Human-readable memory info
free -h
# Detailed breakdown
cat /proc/meminfo
# Check if OOM killer has been triggered
sudo dmesg | grep -i "out of memory"
sudo dmesg | grep -i "killed process"
Understanding the output of free -h:
total used free shared buff/cache available
Mem: 2.0G 1.5G 100M 50M 400M 300M
Swap: 1.0G 500M 500M
• available is the key metric - this is memory actually available for new applications
• If available < 10% of total, you're running low on memory
• If swap usage is high, your system is struggling
Solution 1: Identify Memory Hogs
Find what's using the most memory:
# Top memory consumers (interactive)
top
# Press 'M' to sort by memory usage
# Or use htop (better visualization)
sudo apt install htop -y
htop
# List processes by memory usage
ps aux --sort=-%mem | head -10
# Check memory per process
sudo pmap -x [PID]
Common memory culprits:
- Java applications: JVM heap size too large
- Node.js: Memory leaks or inefficient code
- MySQL/PostgreSQL: Buffer pool/cache too large
- Apache: Too many worker processes
- PHP-FPM: pm.max_children set too high
Solution 2: Configure Swap Memory
Swap acts as emergency memory when RAM is full. Most VPS providers don't enable swap by default.
Check if you have swap:
sudo swapon --show
free -h
Create swap file (recommended: 1-2x your RAM):
# Create 2GB swap file
sudo fallocate -l 2G /swapfile
# Set permissions
sudo chmod 600 /swapfile
# Make it a swap file
sudo mkswap /swapfile
# Enable swap
sudo swapon /swapfile
# Verify
sudo swapon --show
free -h
Make swap permanent:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Optimize swap usage:
# Set swappiness (0-100, lower = use swap less)
sudo sysctl vm.swappiness=10
# Make permanent
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
# Set cache pressure (default is 100)
sudo sysctl vm.vfs_cache_pressure=50
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
Solution 3: Optimize Memory-Hungry Services
MySQL/MariaDB optimization:
Database memory configuration is critical. See our detailed MySQL performance optimization guide for comprehensive tuning.
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
# For a 2GB VPS, use conservative settings:
[mysqld]
innodb_buffer_pool_size = 512M # 25% of total RAM
key_buffer_size = 64M
max_connections = 50
query_cache_size = 0 # Disable in MySQL 8+
tmp_table_size = 32M
max_heap_table_size = 32M
sudo systemctl restart mysql
PHP-FPM optimization:
sudo nano /etc/php/8.1/fpm/pool.d/www.conf
# Reduce max children based on available memory
pm = dynamic
pm.max_children = 15 # Each PHP process ~30-50MB
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6
sudo systemctl restart php8.1-fpm
Apache to Nginx migration:
Apache uses significantly more memory than nginx. If you're running out of memory, consider switching. If you encounter issues after switching, check our nginx 502 error troubleshooting guide.
# Nginx uses ~5-10MB vs Apache's 20-50MB per worker
sudo apt install nginx -y
sudo systemctl disable apache2
sudo systemctl enable nginx
Node.js memory limit:
# Limit Node.js heap size
node --max-old-space-size=512 app.js # 512MB limit
# In PM2:
pm2 start app.js --node-args="--max-old-space-size=512"
Solution 4: Find and Fix Memory Leaks
For Node.js applications:
# Monitor memory over time
pm2 monit
# Check for memory leaks
node --inspect app.js
# Then use Chrome DevTools to profile memory
# Use heap snapshots
const v8 = require('v8');
const fs = require('fs');
const heapdump = v8.writeHeapSnapshot();
fs.writeFileSync('./heap.heapsnapshot', heapdump);
For PHP applications:
# Enable memory limit in PHP
sudo nano /etc/php/8.1/fpm/php.ini
memory_limit = 256M # Prevent runaway scripts
sudo systemctl restart php8.1-fpm
Monitor memory trends:
# Install monitoring
sudo apt install sysstat -y
# Check memory statistics over time
sar -r 1 10 # Check every second for 10 seconds
# Historical data
sar -r
Memory Management Made Simple
VPS Commander provides one-click workflows for memory optimization: configure swap, tune MySQL/PHP, monitor memory usage, and identify resource hogs - all from a user-friendly dashboard.
Optimize Your VPS with VPS CommanderSolution 5: Reduce Memory Usage
Disable unnecessary services:
# List all running services
systemctl list-units --type=service --state=running
# Disable services you don't need
sudo systemctl disable snapd # If you don't use snaps
sudo systemctl disable bluetooth
sudo systemctl stop [service-name]
Use lighter alternatives:
- Instead of Apache: Use nginx
- Instead of MySQL: Use MariaDB or PostgreSQL (better memory management)
- Instead of full desktop environments: Use command-line tools
- Instead of running everything locally: Use managed services (managed databases, CDN, etc.)
Implement caching:
# Install Redis for caching
sudo apt install redis-server -y
# Configure Redis memory limit
sudo nano /etc/redis/redis.conf
maxmemory 256mb
maxmemory-policy allkeys-lru
sudo systemctl restart redis
Solution 6: Upgrade Your VPS Plan
Sometimes the simplest solution is more RAM. Consider upgrading if:
- You've optimized everything and still run out of memory
- Your application legitimately needs more resources
- You're running multiple services on one VPS
- Swap is constantly being used heavily
Monitoring and Prevention
Proactive monitoring prevents memory crises. Learn more in our VPS performance monitoring guide and log files guide.
Set up memory alerts:
# Create a simple monitoring script
cat << 'EOF' > /usr/local/bin/memory-check.sh
#!/bin/bash
THRESHOLD=90
USED=$(free | grep Mem | awk '{print ($3/$2) * 100.0}' | cut -d. -f1)
if [ "$USED" -gt "$THRESHOLD" ]; then
echo "Memory usage is above ${THRESHOLD}%: ${USED}%" | \
mail -s "High Memory Alert" your-email@example.com
fi
EOF
sudo chmod +x /usr/local/bin/memory-check.sh
# Run every 5 minutes
echo '*/5 * * * * /usr/local/bin/memory-check.sh' | sudo crontab -
Use monitoring tools:
- Netdata: Real-time performance monitoring
- Glances: Advanced system monitoring
- Prometheus + Grafana: Enterprise-grade monitoring
Emergency: Server Frozen Due to OOM
If your server is unresponsive due to memory exhaustion:
- Access via your provider's web console
- Reboot the server (last resort)
- Immediately create swap file when it comes back up
- Identify and fix the memory hog before it happens again
- Ensure you have recent backups - check our VPS backup guide
Quick Reference Checklist
- ✅ Check current memory usage:
free -h - ✅ Identify memory hogs:
ps aux --sort=-%mem | head - ✅ Create/configure swap file
- ✅ Optimize database settings (MySQL/PostgreSQL)
- ✅ Tune PHP-FPM worker processes
- ✅ Consider switching Apache → nginx
- ✅ Set memory limits for applications
- ✅ Disable unnecessary services
- ✅ Set up memory monitoring
- ✅ Consider upgrading VPS plan if needed
Conclusion
Out of memory errors are frustrating but usually fixable. Follow this approach:
- Immediate fix: Add swap memory to prevent crashes
- Short-term: Identify and optimize memory-hungry processes
- Long-term: Monitor usage, set up alerts, and right-size your VPS
Remember: swap is a band-aid, not a cure. Always investigate why you're running out of memory and optimize accordingly.