Tutorial 📅 January 2025 📖 8 min read

Out of Memory Error - Causes & Fixes (2025)

Fix OOM (Out of Memory) errors on your VPS. Identify memory hogs, configure swap, and prevent crashes. Complete guide.

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
What to look for:
• 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:

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
Important: Swap is slower than RAM. It prevents crashes but doesn't solve the root cause. Still optimize your applications!

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 Commander

Solution 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:

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:

Cost comparison: Most providers charge $2-5 per month for each additional GB of RAM. Upgrading from 1GB to 2GB typically costs $5-10/month - often worth it for the peace of mind.

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:

Emergency: Server Frozen Due to OOM

If your server is unresponsive due to memory exhaustion:

  1. Access via your provider's web console
  2. Reboot the server (last resort)
  3. Immediately create swap file when it comes back up
  4. Identify and fix the memory hog before it happens again
  5. Ensure you have recent backups - check our VPS backup guide

Quick Reference Checklist

  1. ✅ Check current memory usage: free -h
  2. ✅ Identify memory hogs: ps aux --sort=-%mem | head
  3. ✅ Create/configure swap file
  4. ✅ Optimize database settings (MySQL/PostgreSQL)
  5. ✅ Tune PHP-FPM worker processes
  6. ✅ Consider switching Apache → nginx
  7. ✅ Set memory limits for applications
  8. ✅ Disable unnecessary services
  9. ✅ Set up memory monitoring
  10. ✅ Consider upgrading VPS plan if needed

Conclusion

Out of memory errors are frustrating but usually fixable. Follow this approach:

  1. Immediate fix: Add swap memory to prevent crashes
  2. Short-term: Identify and optimize memory-hungry processes
  3. 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.