Add swap
A swap file as a buffer for tight RAM, tuning swappiness, and checking it.
3 min read
On this page
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
swapon --show
free -hIf 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:
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfilechmod 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:
cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' >> /etc/fstabCheck the line before you reboot:
tail -n 3 /etc/fstab
findmnt --verifyfindmnt --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:
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swappiness.conf
sysctl --systemCheck that it worked
swapon --show
free -h
cat /proc/sys/vm/swappinessExpected: /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
swapoff /swapfile
rm /swapfileTo 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
| Message | Cause and fix |
|---|---|
swapon: /swapfile: insecure permissions 0644 | chmod 600 /swapfile. |
swapon: /swapfile: swapon failed: Invalid argument | The 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 device | Not enough space. df -h / shows free space; use a smaller file. |
| Server is very slow despite swap | It is swapping constantly. Check free -h and top; the RAM isn't enough for the workload. |