Prerequisites
Before adding swap, make sure you have:
- SSH access to your VPS
- Root or sudo privileges
- At least 10-20% free disk space
💡 Swap is disk space used as emergency RAM. It is slower but prevents crashes when physical RAM is full.
Step 1: Check Current Swap
ssh hxroot@YOUR_SERVER_IP -p 22swapon --showfree -hStep 2: Create a Swap File
To add 2GB of swap:
sudo fallocate -l 2G /swapfileIf fallocate not available:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048Step 3: Set Correct Permissions
sudo chmod 600 /swapfileStep 4: Format as Swap
sudo mkswap /swapfileStep 5: Enable Swap
sudo swapon /swapfileStep 6: Make Permanent (Survive Reboot)
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstabStep 7: Verify
free -hswapon --showHow Much Swap to Add?
- RAM ≤ 2GB → Swap = 2x RAM
- RAM 2-8GB → Swap = same as RAM
- RAM 8-64GB → Swap = 4-8GB
- RAM > 64GB → Swap = 4GB minimum
Adjust Swappiness (How Often Swap is Used)
cat /proc/sys/vm/swappinessDefault is 60. Lower values reduce swap usage (good for SSDs):
sudo sysctl vm.swappiness=10Make permanent:
echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.confRemove Swap (If Needed)
sudo swapoff /swapfilesudo rm /swapfileRemove the line from /etc/fstab.
✅ Swap space has been added successfully.