May 23, 2026Guides
How to Add Swap Space on Linux VPS
Prevent out-of-memory errors on small VPS by creating and enabling swap file with swappiness tuning.

VPS plans with limited RAM can run out of memory under load. Swap uses disk space as virtual memory and helps prevent crashes. This guide shows how to add a swap file on Ubuntu and CentOS.
Check current swap
bash
free -h
swapon --show
# If Swap shows 0, you need to add swapCreate swap file (2 GB example)
Size depends on RAM — often 1–2× RAM for small VPS, or 1 GB minimum:
bash
sudo fallocate -l 2G /swapfile
# If fallocate fails:
# sudo dd if=/dev/zero of=/swapfile bs=1M count=2048
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
free -hMake swap permanent
Add to /etc/fstab so swap activates after reboot:
bash
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
sudo swapon --showTune swappiness
Value 10–60 is common for servers (default 60). Lower = less aggressive swap use:
bash
sudo sysctl vm.swappiness=10
# Permanent:
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
sudo sysctl -pImportant notes
- Swap is slower than RAM — optimize apps, do not rely only on swap
- SSD swap is acceptable; monitor disk I/O on busy servers
- Remove swap: sudo swapoff /swapfile && sudo rm /swapfile
- For 512 MB RAM VPS, 1 GB swap is a practical minimum
- Consider upgrading RAM if swap is constantly full