A VPS with 1 or 2 GB of memory can run out of RAM during a software update, a build or a traffic spike. When that happens Linux stops a program to free memory, and it is often your database or your app. Swap is disk space the system can use as extra, slower memory. It does not replace RAM, but it gives you a safety margin.
Before you start, connect to your VPS with SSH.
1. Check whether you already have swap
free -h
swapon --show
If the Swap line shows 0B and swapon --show prints nothing, there is no swap.
2. Create the swap file
This makes a 2 GB file. Use 1G if your disk is small, and never more than a quarter of your free disk space.
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
The chmod 600 step matters: only root should be able to read the swap file.
3. Keep it after a reboot
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
4. Tell Linux to use swap only when needed
The default setting is 60, which swaps early. For a server a lower value is better:
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system
5. Check that it works
free -h
cat /proc/sys/vm/swappiness
The Swap line should now show 2.0Gi, and swappiness should be 10.
Remove it later
sudo swapoff /swapfile
sudo rm /swapfile
Then delete the /swapfile line from /etc/fstab.
Good to know
- Swap on a busy server is a sign that you need more memory. If the Swap "used" number keeps growing, move up a plan. See how much RAM and CPU a VPS needs.
- Swap is slow compared with RAM. It keeps a spike from crashing your server, but it does not make a too-small server fast.
Run it on your own VPS
Cloud VPS plans: If swap is always busy, a bigger plan is the real fix. Prices are in rupees, you can pay by UPI, and you get a GST invoice.