Skip to content

How to add swap to a VPS

Create a swap file so the server doesn't crash when it runs out of memory, and tune swappiness.

Updated: 2026-11-07 · 1 min read

Swap is disk space the system uses when RAM runs out. It doesn't replace RAM, but it protects processes from being killed suddenly (OOM killer) during peaks, such as a project build or a package upgrade.

Check whether swap exists

swapon --show
free -h

If swapon prints nothing, swap isn't configured.

Create a swap file

A size equal to your RAM is usually enough, but no more than 4–8 GB. Example for 2 GB:

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

To enable swap after a reboot, add a line to /etc/fstab:

echo '/swapfile none swap sw 0 0' >> /etc/fstab

Tune swappiness

vm.swappiness controls how eagerly the kernel uses swap (0–100). For servers on SSD we recommend 10:

sysctl vm.swappiness=10
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swap.conf

How to tell you're short on memory

free -h
vmstat 5

If swap is constantly full and the si and so columns in vmstat keep growing, the server needs more RAM. It's better to add memory — message support, it takes a few minutes.

Removing swap

swapoff /swapfile
rm /swapfile
sed -i '/swapfile/d' /etc/fstab