Virteche
Guideschevron_rightServers

Servers · 5 min read · Updated

How to Add Swap on Ubuntu and Debian

Swap is disk space the kernel uses as overflow when memory runs out, so a brief spike slows the server down instead of getting a process killed. Check what you have with swapon --show. To add a 2 GB swap file on Ubuntu or Debian, run fallocate, chmod 600, mkswap and swapon, then add one line to /etc/fstab so it comes back after a reboot. Keep vm.swappiness low so swap stays a safety net.

1. Check What You Have

swapon --show
free -h

If swapon --show lists a swap partition or file already, you only need this guide to add more. If it prints nothing, the server has no swap.

2. Create and Turn On a Swap File

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
swapon --show

chmod 600 matters: swap can contain anything that was in memory, including passwords, so only root may read it.

3. Keep It After a Reboot

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
sudo findmnt --verify

findmnt --verify checks /etc/fstab for mistakes before a reboot finds them for you.

4. Set Swappiness

Swappiness (0 to 200, default 60) is how readily the kernel moves memory to swap. On a server, a low value keeps working memory in RAM and uses swap only under pressure:

echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system
cat /proc/sys/vm/swappiness

If Swap Is Always in Use

Watch vmstat 5 for a minute. Non-zero numbers in the si and so columns all the time mean the server is constantly moving memory to and from disk. That is the point to find what is using the memory (top, sorted with M) or move to a bigger plan. How much CPU and RAM does a VPS need? has rough sizes by workload.

Common Questions

  • How much swap should a server have?

    Enough to absorb a short spike, not to run on: 1 to 2 GB is plenty for most servers, whatever their memory. A server that uses swap all the time needs more memory, not more swap.

  • Does swap slow the server down?

    Only when it is in use. Swap on NVMe is far faster than on old spinning disks, but still much slower than memory. With a low swappiness the kernel only uses it under real memory pressure.

  • What happens without swap when memory runs out?

    The kernel's out-of-memory killer stops a process, usually the biggest one, which is often your database. dmesg or journalctl -k shows “Out of memory: Killed process” when it has happened.

  • How do I remove the swap file?

    Run sudo swapoff /swapfile, delete the /swapfile line from /etc/fstab, then sudo rm /swapfile.

KVM servers from 6 GB of memory, on NVMe storage, in Ashburn and Dallas.

See VPS plans

Keep Reading

All guides