Add swap memory to a small VPS
Updated 27 Nov 2026
Swap is disk space the server uses as extra memory when its RAM is full. On a small VPS with 1 or 2 GB of RAM, it stops sudden crashes during updates, builds or busy moments. It's slower than real RAM, so it's a safety net, not a replacement for a bigger plan.
1. Check whether you already have swap
sudo swapon --show
free -h
If swapon prints nothing and the Swap line in free -h shows 0B, there's no swap yet.
2. Check you have free disk space
df -h /
Use this as a guide for the swap size:
| RAM | Swap |
|---|---|
| 1 GB | 1 to 2 GB |
| 2 GB | 2 GB |
| 4 GB or more | 2 to 4 GB |
3. Create the swap file
This makes a 2 GB file. Change 2G to the size you want.
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
chmod 600 makes sure only root can read the file, as it may hold copies of memory.
If fallocate fails, use this slower command instead (2048 MB):
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
Then run the chmod, mkswap and swapon lines again.
4. Check it works
sudo swapon --show
free -h
You should see /swapfile and the new size on the Swap line.
5. Keep it after a restart
Add the swap file to /etc/fstab so it switches on every time the server starts:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Run this line only once. Running it twice adds a duplicate entry. Check with
cat /etc/fstab.
6. Use swap only when needed
By default, Linux starts using swap fairly early. On a server, it's better to keep things in RAM and use swap only when memory is nearly full:
sudo sysctl vm.swappiness=10
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
The first line changes it now; the second keeps it after a restart.
How to tell if you need more RAM
Swap that's used a little is fine. If free -h shows swap nearly full most of the time, or the server feels slow while top shows high wa (waiting for disk), the server needs more memory. Upgrade to a bigger plan rather than adding more swap. See Check why your server is slow.
Remove swap
sudo swapoff /swapfile
sudo rm /swapfile
Then remove the /swapfile line from /etc/fstab with sudo nano /etc/fstab.
Need a server? Order a Cloud VPS and get root access within minutes. For help, open a ticket and choose Technical.