Swap is disk space Linux can use as overflow memory when physical RAM is exhausted. It won't make your VPS faster, but it prevents applications from being killed outright during short memory spikes — a useful safety net, especially on smaller VPS plans.
Prerequisites
- Ubuntu or Debian VPS
- Root or sudo access
- Sufficient free disk space
Step 1 — Check Existing Swap
swapon --show
free -h
If nothing is listed under Swap, none is currently configured.
Step 2 — Check Available Disk Space
df -h
Step 3 — Create a Swap File
This example creates a 2 GB swap file:
sudo fallocate -l 2G /swapfile
If fallocate isn't supported on your filesystem:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
Step 4 — Secure the Swap File
sudo chmod 600 /swapfile
Step 5 — Format and Enable It
sudo mkswap /swapfile
sudo swapon /swapfile
Step 6 — Verify
swapon --show
free -h
Step 7 — Make It Permanent (Survive Reboots)
sudo nano /etc/fstab
Add this line:
/swapfile none swap sw 0 0
Step 8 — Tune Swappiness (Optional)
Swappiness controls how aggressively Linux uses swap versus RAM (0-100). Lower values favor RAM:
cat /proc/sys/vm/swappiness
Set it temporarily:
sudo sysctl vm.swappiness=10
Make it permanent:
echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf
How Much Swap Do You Need?
| RAM | Suggested Swap |
|---|---|
| 1–2 GB | 1–2 GB |
| 4 GB | 2–4 GB |
| 8 GB+ | 1–2 GB (used only as a safety net) |
Disabling and Removing Swap
sudo swapoff /swapfile
sudo rm /swapfile
Also remove the corresponding line from /etc/fstab.
Common Errors
Swap not active after reboot — confirm the /etc/fstab entry was added correctly and test with sudo mount -a.
No space left on device — free up disk space before creating the swap file.
Best Practices
- Treat swap as a safety buffer, not a substitute for adequate RAM
- Monitor with
free -h— persistent heavy swap usage means you likely need more RAM - Use restrictive
600permissions on the swap file
FAQ
Does swap slow down my VPS?
Swap itself is idle unless actively used; heavy, sustained swapping is slower than RAM and indicates memory pressure that's worth investigating.
Continue Reading
- How to Check VPS Resource Usage (CPU, RAM, Disk)
- How to Find and Stop Processes Using Too Many Resources
- How to Choose the Right VPS Plan for Your Workload
Browse more articles in Linux Server Administration.
