When You Need Swap
Swap is a disk area that Linux uses as an extension of RAM. When RAM runs out, the system moves unused memory pages to swap instead of killing processes via the OOM-killer. Swap is critical on servers with low RAM (1–2 GB) and for workloads with peak memory consumption. However, swap is an order of magnitude slower than RAM, even on NVMe SSD. Use it as a safety net, not as a replacement for RAM. If the server constantly uses swap — it's time to upgrade your plan.
Creating a Swap File
Recommended swap size: for servers with 1–2 GB RAM — equal to the RAM amount; for 4+ GB — 2 GB is usually enough. Run in order:
sudo fallocate -l 2G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile
Verify:
free -h
The Swap row should show the size. These commands activate swap until reboot; for permanent setup, add an entry to fstab.
Auto-Mount via fstab
To have swap activated on boot, make a backup and add a line to
/etc/fstab:sudo cp /etc/fstab /etc/fstab.bak echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Verify correctness:
sudo findmnt --verify
If there are no errors, swap will mount automatically on the next reboot.
Configuring Swappiness
The
vm.swappiness parameter controls how aggressively the kernel uses swap. Value from 0 to 100, default is 60. For servers, 10–20 is recommended.
Temporarily:sudo sysctl vm.swappiness=10
Permanently — add to
/etc/sysctl.conf:vm.swappiness=10
Apply:
sudo sysctl -p
Monitoring Swap Usage
To check total swap volume and usage, run:
free -h
For more detail:
swapon --show
This displays all active swap partitions/files. To see page exchange dynamics (si and so columns — swap in and swap out):
vmstat 1 5
If si/so are consistently non-zero, the server is actively swapping, which slows things down. For real-time monitoring, use:
htop
The top panel shows RAM and Swap bars with usage percentages.