Small servers run out of memory at the worst moments: an apt upgrade, a Docker build, a nightly backup. Without swap the kernel's OOM killer picks a process and ends it — often your database. A swap file is a cheap seatbelt that gives those spikes somewhere to go. It takes five commands.
1. Check what you have
swapon --show
free -h
No output from swapon --show means there's no swap yet.
2. Create the swap file
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
chmod 600 matters: swap can contain fragments of anything in memory, including secrets, so only root may read it. If fallocate fails with "operation not supported", use dd instead:
dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
3. Make it permanent
Without this step, swap disappears after a reboot:
echo '/swapfile none swap sw 0 0' >> /etc/fstab
4. Tune swappiness
Tell the kernel to prefer RAM and use swap mainly under pressure:
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swap.conf
sysctl --system
5. Verify
swapon --show
free -h
You should see a 2 GB swap device, and cat /proc/sys/vm/swappiness should print 10.
How big should it be?
- 1–2 GB RAM server: 1–2 GB swap.
- 4 GB and more: 1–2 GB is still enough as a safety net.
Don't size swap to "twice the RAM". On a server, swap exists to absorb short spikes, not to run workloads that don't fit.
When swap isn't the answer
Watch it for a few days:
vmstat 5
The si and so columns show pages swapped in and out per second. Occasional activity is fine. Constant non-zero values mean the server is short of memory and everything is waiting on disk. At that point the fix is more RAM — see how much RAM a VPS needs. On EQVPS you can move to a bigger plan without reinstalling; your data stays.
Comments
No comments yet. Be the first.