Skip to content
CitexNode
All guides

Add swap

A swap file as a buffer for tight RAM, tuning swappiness, and checking it.

3 min read

Applies to Debian 12/13, Ubuntu 22.04/24.04, AlmaLinux 9 and Rocky Linux 9.

Swap is disk space Linux uses when RAM is full. It is much slower than RAM, but it stops the kernel from killing a program outright during a short spike (Out of memory: Killed process …). Swap doesn't replace RAM: if your server needs more permanently, choose a bigger plan.

1. Check whether swap exists

bash
swapon --show
free -h

If swapon --show prints nothing and the Swap: line in free shows 0B everywhere, the server has none yet.

2. Create a swap file

Rule of thumb: as large as the RAM, at most 4 GB. Here 2 GB:

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

chmod 600 matters: passwords and other data from RAM can end up in swap.

3. Make it permanent

So the swap is back after a reboot:

bash
cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' >> /etc/fstab

Check the line before you reboot:

bash
tail -n 3 /etc/fstab
findmnt --verify

findmnt --verify must not report errors. A typo in /etc/fstab can stop the server from booting; then the Console in the dashboard helps, and the backup /etc/fstab.bak is ready.

4. Set swappiness

vm.swappiness controls how early Linux swaps (0 to 100, default 60). For a server with swap as an emergency reserve, 10 is a good value:

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

Check that it worked

bash
swapon --show
free -h
cat /proc/sys/vm/swappiness

Expected: /swapfile with 2G in the list, a Swap: line with 2.0Gi in free, and 10 for swappiness. After a reboot, all three must look the same.

Resize or remove

bash
swapoff /swapfile
rm /swapfile

To enlarge, repeat step 2 with the new size; the line in /etc/fstab stays the same. To remove, also delete the /swapfile … line from /etc/fstab.

swapoff needs as much free RAM as is currently in swap. If RAM is full, stop programs first.

Common errors

MessageCause and fix
swapon: /swapfile: insecure permissions 0644chmod 600 /swapfile.
swapon: /swapfile: swapon failed: Invalid argumentThe file has holes. Delete it and recreate it with dd if=/dev/zero of=/swapfile bs=1M count=2048 instead of fallocate, then chmod, mkswap, swapon.
fallocate: fallocate failed: No space left on deviceNot enough space. df -h / shows free space; use a smaller file.
Server is very slow despite swapIt is swapping constantly. Check free -h and top; the RAM isn't enough for the workload.

What next

  • Keep an eye on RAM: the Usage tab of your VPS in the dashboard.
  • More RAM: the plans under /vserver.
  • Help: ticket.