When Should You Add Swap?
If your VPS has 1-2 GB RAM, swap can prevent abrupt process kills during bursts. Swap is slower than RAM, but better than crashes, especially for occasional spikes.
Step 1: Check Current Memory and Swap
free -h
swapon --show
Step 2: Create a Swap File
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Verify:
swapon --show
free -h
Step 3: Make Swap Persistent
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Step 4: Tune Swappiness and Cache Pressure
sudo sysctl vm.swappiness=10
sudo sysctl vm.vfs_cache_pressure=50
# persist settings
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
How Much Swap Should You Use?
- 1 GB RAM VPS: 1-2 GB swap
- 2 GB RAM VPS: 2 GB swap
- 4 GB+ RAM VPS: 1-2 GB safety swap usually enough
FAQ
Does swap make my VPS faster?
No. Swap prevents crashes; it does not improve performance. If swap usage is constantly high, upgrade RAM.
Can I remove swap later?
Yes. Use sudo swapoff /swapfile, remove the fstab entry, then delete the file.
Is zram better than swap file?
For some workloads yes, but swap file is simpler and reliable as a default setup across providers.
For full stability, combine swap with resource monitoring and proactive alerts.