Prerequisites
Before adding swap memory, make sure you have:
- SSH access to your VPS (username:
hxroot) - Your server IP address and root password
- At least 10-20% free disk space for swap file
💡 What is Swap? Swap is disk space used as virtual RAM when physical memory is full. It prevents crashes but is slower than real RAM.
Step 1: Check Current Swap Usage
Connect to your VPS:
ssh hxroot@YOUR_SERVER_IP -p 22Check memory and swap status:
free -hExample output with no swap:
total used free shared buff/cache available
Mem: 3.8G 2.1G 1.1G 123M 700M 1.4G
Swap: 0B 0B 0BStep 2: Check Disk Space
df -hEnsure you have enough free space for the swap file (recommended 1-2x RAM).
Step 3: Create Swap File
For a 2GB swap file (adjust size as needed):
sudo fallocate -l 2G /swapfileIf fallocate is not available, use dd:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048Step 4: Set Correct Permissions
sudo chmod 600 /swapfileOnly root should read/write swap file for security.
Step 5: Format as Swap
sudo mkswap /swapfileExample output:
Setting up swapspace version 1, size = 2 GiB (2147483648 bytes)
no label, UUID=abc123-def456-ghi789Step 6: Enable Swap
sudo swapon /swapfileStep 7: Verify Swap is Active
free -hShould now show swap space:
total used free shared buff/cache available
Mem: 3.8G 2.1G 1.1G 123M 700M 1.4G
Swap: 2.0G 0B 2.0GAlso check with:
sudo swapon --showStep 8: Make Swap Permanent (Auto-mount on Boot)
Add to /etc/fstab:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstabVerify the entry:
cat /etc/fstab | grep swapHow Much Swap Should You Add?
General guidelines:
- RAM ≤ 2GB → Swap = 2x RAM
- RAM 2GB - 8GB → Swap = same as RAM
- RAM 8GB - 64GB → Swap = 4GB to 8GB
- RAM > 64GB → Swap = 4GB minimum
Hostxpeed VPS recommendations:
- 2GB RAM VPS → 2GB swap
- 4GB RAM VPS → 4GB swap
- 8GB RAM VPS → 4GB swap
- 16GB+ RAM VPS → 4-8GB swap
Adjust Swappiness (How Often Swap is Used)
Swappiness value (0-100, default 60):
cat /proc/sys/vm/swappinessTo reduce swap usage (for servers with enough RAM):
sudo sysctl vm.swappiness=10Make permanent by adding to /etc/sysctl.conf:
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.confRemove Swap (If Needed)
To disable and remove swap:
sudo swapoff /swapfilesudo rm /swapfileRemove the line from /etc/fstab.
Monitor Swap Usage
Check swap in real-time:
free -h -s 5See which processes use swap:
sudo smem --swapOr:
for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file 2>/dev/null; done | sort -k 2 -n -r | head -10✅ Swap memory has been added successfully. Your server can now use disk space as emergency RAM when physical memory is full.