Swap is disk space the kernel uses when RAM runs out. It is much slower than memory, but a small swap file stops a short memory spike from triggering the OOM killer and crashing MySQL or your app. Here is how to create a swap file on a Linux VPS and keep it sensible.
Before you start
- Root or sudo access.
- Free disk space for the swap file (
df -h /). - Check whether swap already exists:
swapon --showandfree -h.
Choose a swap size
| VPS RAM | Suggested swap |
|---|---|
| 1–2 GB | 1–2 GB |
| 4–8 GB | 2 GB |
| 16 GB+ | 2–4 GB (safety net only) |
Swap is a cushion, not extra RAM. If the server swaps constantly, it needs more memory or less load.
Create the swap file
- Allocate the file (2 GB here):If
fallocate -l 2G /swapfilefallocatefails (some filesystems), usedd if=/dev/zero of=/swapfile bs=1M count=2048. - Restrict permissions so other users cannot read memory contents:
chmod 600 /swapfile - Format and enable it:
mkswap /swapfile && swapon /swapfile - Confirm with
swapon --show.
Make swap permanent
Add a line to /etc/fstab so it comes back after reboot:
/swapfile none swap sw 0 0Test the fstab file without rebooting: swapoff /swapfile && swapon -a && swapon --show.
Tune swappiness
vm.swappiness (0–100) controls how eagerly the kernel swaps. Servers usually do better with a low value:
sysctl vm.swappiness=10Make it permanent:
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swap.confResize or remove swap
- Turn it off (needs enough free RAM to absorb what is in swap):
swapoff /swapfile - To resize, recreate it:
fallocate -l 4G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile - To remove, delete the fstab line, then
rm /swapfile.
Check memory and swap use
free -hshows total, used and available memory and swap.vmstat 5: thesi/socolumns show swap in/out per second. Constant non-zero values mean memory pressure.- See which processes use swap:
for f in /proc/*/status; do awk '/VmSwap|Name/{printf $2" "}END{print ""}' $f; done | sort -k2 -n | tail
Troubleshooting
- swapon: Invalid argument: the file has holes (common with fallocate on some filesystems); recreate it with
dd. - swapon: Operation not permitted: container-based VPS (OpenVZ/LXC) cannot add swap; it is controlled by the host.
- Server still killed by OOM: swap delays the problem; find the memory-hungry process and reduce its limits.
Swap FAQ
Does swap slow down my server?
Only when it is actively used. Unused swap costs nothing but disk space.
Is swap bad for NVMe drives?
Occasional swapping is fine for modern NVMe drives. Constant heavy swapping means you need more RAM anyway.
Swap file or swap partition?
A swap file is easier to create and resize and performs the same on modern kernels.
