How to Add Swap Space on an Ubuntu Server (and When You Shouldn't)
⏱️ 2 min read
Cloud servers with 512MB-1GB of RAM die to OOM killers the first time a build or backup spikes memory. Swap gives the kernel a pressure valve. It's not a substitute for RAM, but on a small VPS it's often the difference between a hiccup and a 3am pager.
The five commands
sudo fallocate -l 1G /swapfile (or dd if=/dev/zero of=/swapfile bs=1M count=1024 if fallocate isn't available) → sudo chmod 600 /swapfile → sudo mkswap /swapfile → sudo swapon /swapfile → verify with free -m. To survive reboots, add /swapfile none swap sw 0 0 to /etc/fstab.
Tuning the two knobs
swappiness (vm.swappiness, default 60) controls how eagerly the kernel swaps. On app servers, 10 is the common setting — swap only under real pressure. cache pressure (vm.vfs_cache_pressure) matters less; leave it unless you've measured. Both go in /etc/sysctl.conf, then sudo sysctl -p.
When swap is the wrong answer
Swap hides leaks and throttles databases — Postgres and MySQL both perform badly once active working set pages hit swap. If your server swaps steadily at idle, you have a leak or a sizing problem, and the fix is profiling (smem, ps aux --sort=-rss) or a bigger plan, not a bigger swapfile. Swap is for bursts: builds, backups, deploys.
Also: swap on SSDs is fine for burst use; don't put swap on network storage, ever. And a containerized wrinkle — swap must be enabled on the host, not in the container; Kubernetes workloads need swap handling enabled or better, no swap with correctly sized limits.
Get the sizing right
Rule of thumb: RAM × 2 for small servers (up to 4GB RAM), 4GB max otherwise. Benchmarking what your workload actually needs? A cheap hourly VPS — like these — lets you measure before you commit.