FAQ VPS & Servers

How to add swap space to a VPS

Creating a swap file with fallocate and mkswap, making it permanent in fstab, and why swap is a cushion rather than a substitute for RAM.

Updated 5 min read Beginner

Create a swap file with fallocate, format it with mkswap, enable it with swapon, and add it to /etc/fstab so it comes back after a reboot. Swap is disk space the kernel uses as overflow when physical memory runs out — much slower than RAM, but far better than a process being killed outright when memory is exhausted.

Create and enable the swap file

This example creates a 2 GB swap file — adjust the size to your server:

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

chmod 600 matters before mkswap — a world-readable swap file is a real information leak, since anything held in memory, including secrets, can be written out to it.

If fallocate is not supported on your filesystem — some configurations reject it with an error — fall back to dd, which is slower but works everywhere:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

Make it survive a reboot

A swap file created this way is active only until the next reboot unless you add it to /etc/fstab:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Confirm it is working

swapon --show
free -h

free -h should now show a non-zero total under Swap.

How much swap do you actually need?

There is no universal rule, but a reasonable starting point on a small VPS is swap equal to your total RAM, up to about 4 GB, beyond which more swap mostly just delays an out-of-memory situation rather than preventing it — a server that is genuinely and consistently short of memory needs more RAM, not more swap. See how much RAM does my VPS need? for sizing guidance, and current RAM tiers at /vps-hosting.

Adjusting swappiness

Swappiness controls how eagerly the kernel moves memory to swap before it is strictly necessary, on a scale of 0 to 100. On a server, lower values are usually preferable — swap should be a safety net for genuine memory pressure, not something the kernel reaches for routinely while RAM is still available:

sudo sysctl vm.swappiness=10

That change only lasts until reboot. Make it permanent by adding it to /etc/sysctl.conf:

echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
Swap is not a substitute for RAM

Swap lives on disk, which is orders of magnitude slower than memory even on fast SSD-backed storage. A server that is relying on swap heavily, rather than occasionally, will feel sluggish across everything it runs. Treat swap as a cushion against a short-lived spike, and treat sustained swap usage as a sign the server needs more memory, not more swap.

Related reading