← Back to all posts

How to Add Swap Space on an Ubuntu Server (and When You Shouldn't)

Published October 1, 2026

⏱️ 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.

Partner pick — sponsored

Sentry — our error-tracking pick for this stack

See the exact line of code that broke — before your users report it. Free tier for small teams.

Get Sentry →
Also vetted

Vultr — Spin a disposable box to replay this failure without touching prod.

Get Vultr →

We earn a commission if you buy through our links — it never costs you extra. More vetted tools on our picks hub · comparing clouds? DigitalOcean vs Vultr and vs AWS · full deals: DigitalOcean · Vultr · NordLayer · Semrush

#AmazonAssociate — As an Amazon Associate I earn from qualifying purchases. Full disclosure →