How to Set Up a Swap File on Your VPS (Prevent Out of Memory Crashes)

Estimated reading: 2 minutes

A swap file lets your VPS use disk space as overflow RAM. On plans with 512MB–1GB of RAM, adding swap prevents MySQL, PHP, and other services from crashing when memory gets tight.

Step 1: Check If Swap Already Exists

swapon --show
free -h

If the swap row shows 0B or nothing, there’s no swap configured. Proceed below.

Step 2: Create the Swap File

Create a 2GB swap file (recommended for 1GB RAM VPS plans):

sudo fallocate -l 2G /swapfile

If fallocate fails, use dd instead:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

Step 3: Secure and Enable the Swap File

# Set correct permissions (only root can read it)
sudo chmod 600 /swapfile

# Format it as swap
sudo mkswap /swapfile

# Enable the swap file
sudo swapon /swapfile

Verify it’s active:

free -h

You should now see swap space listed.

Step 4: Make Swap Permanent (Survive Reboots)

Add the swap file to /etc/fstab so it persists after a reboot:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Step 5: Tune Swappiness (Optional)

Swappiness controls how aggressively the system uses swap (0–100). The default is 60. For a server, 10 is recommended so the system prefers using RAM and only falls back to swap when necessary:

# Check current value
cat /proc/sys/vm/swappiness

# Set to 10 for this session
sudo sysctl vm.swappiness=10

# Make it permanent
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

Note on VPS Swap

Swap on a VPS uses your disk (usually SSD), which is slower than RAM. It’s a safety net, not a replacement for RAM. If you find yourself relying on swap constantly, consider upgrading your VPS plan for better performance.