How to Fix Nginx Out of Memory (OOM) on DigitalOcean Droplet


The Root Cause: DigitalOcean Droplets, particularly smaller tiers, often have limited RAM resources, making them susceptible to memory exhaustion. This constraint, combined with Nginx’s default worker process settings or unexpected traffic spikes, can lead to processes consuming all available memory and triggering an OOM kill.

Quick Fix (CLI): To immediately alleviate Nginx OOM issues, increasing swap space provides a temporary buffer for memory-intensive operations, buying time for configuration adjustments.

# Check existing swap (optional)
sudo swapon --show

# Create a 2GB swap file (adjust size as needed, e.g., 4G)
sudo fallocate -l 2G /swapfile

# Set correct permissions for the swap file
sudo chmod 600 /swapfile

# Format the file for swap
sudo mkswap /swapfile

# Enable the swap file
sudo swapon /swapfile

# Make swap persistent across reboots by adding to /etc/fstab
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Restart Nginx after adding swap (optional, but recommended if Nginx was thrashing)
sudo systemctl restart nginx

Configuration Check: Edit the main Nginx configuration file, typically /etc/nginx/nginx.conf, to adjust the number of worker processes. This is often the primary cause of OOM on resource-constrained systems.

  • File to edit: /etc/nginx/nginx.conf

  • Lines to change: Locate the worker_processes directive within the main context and modify it. For small droplets (e.g., 1-2GB RAM), 1 or auto (which usually defaults to CPU cores) is recommended. If auto still causes OOM, reduce it to 1.

    # Before: (e.g., worker_processes auto;)
    # After:
    worker_processes 1; # Adjust based on droplet resources. For 1-2GB RAM droplets, 1 is often safer.
    
    # Additionally, if memory pressure persists under high traffic, consider reducing worker_connections.
    # http {
    #     ...
    #     events {
    #         worker_connections 768; # Default is often 1024. Reduce if memory pressure is severe.
    #     }
    #     ...
    # }

Verification: After applying configuration changes, verify Nginx syntax and restart the service. Monitor system memory and kernel logs for any OOM events.

# Test Nginx configuration for syntax errors
sudo nginx -t

# If syntax is OK, reload/restart Nginx
sudo systemctl reload nginx # Use 'restart' if worker_processes was changed, 'reload' for minor config changes.

# Verify the Nginx service status
sudo systemctl status nginx

# Check available memory and swap
free -h

# Check kernel logs for "Out of Memory" killer events
sudo dmesg -T | grep -i 'out of memory'
# Or for recent events:
sudo journalctl -xe | grep -i 'killed process'