How to add swap on Ubuntu
Swap is disk space used as virtual memory when RAM starts to run low. It is not as fast as real memory, but it can help you:
avoid sudden process kills during memory pressure
improve stability on smaller VPS plans
absorb short usage spikes
When it makes sense
Swap is especially useful on VPS plans with limited memory, such as 1–2 GB RAM. That said, if your workload constantly needs more RAM than the server has, swap is not a real substitute for upgrading.
1. Check current memory and swap
free -h
swapon --showIf swapon --show returns nothing, no active swap is configured.
2. Create a swap file
Example for a 2 GB swap file:
sudo fallocate -l 2G /swapfileIf fallocate does not work in your environment, use:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress3. Set secure permissions
4. Format the file as swap
5. Enable swap
Verify it:
6. Make it persistent after reboot
Edit /etc/fstab:
Add this line at the end:
7. Optional: tune swappiness
The swappiness value controls how aggressively Linux uses swap. Check the current value:
For many VPS servers, a value like 10 or 20 is reasonable.
Apply it temporarily:
Make it persistent:
Choosing a swap size
There is no perfect rule, but a practical guideline is:
1 GB RAM → 1–2 GB swap
2 GB RAM → 2 GB swap
4 GB RAM or more → 1–2 GB swap as a small buffer if needed
Best practices
Do not treat swap as the main fix for not having enough RAM.
Monitor actual usage with
htop,free -h, orvmstat.If the server swaps heavily all the time, performance can drop sharply.
How to remove swap
If you want to disable it later:
Then remove the corresponding line from /etc/fstab.
Conclusion
A properly configured swap file can make a small VPS more stable, especially during brief memory spikes.
Last updated