How to Add Swap Space on Ubuntu: Fix Out-of-Memory Errors on Your VPS Print

  • 0

Your app crashed overnight, the log ends with “Killed”, and dmesg mentions the OOM killer? Your server ran out of memory, and the kernel executed the biggest process to survive — usually MySQL or your application. On small VPS plans, swap space is the cheap insurance against exactly this. Ubuntu cloud images ship with no swap at all by default, so let's fix that in five minutes.

Step 1 — Check whether you already have swap

free -h
swapon --show

If the Swap line shows 0B, continue.

Step 2 — Create the swap file

Rule of thumb for servers: swap = RAM for machines up to 2 GB; half the RAM (capped around 4 GB) beyond that.

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Creating a 2GB swap file with fallocate and mkswap on Ubuntu

The chmod 600 matters — swap can contain fragments of any process's memory, including secrets, so only root may read it.

Step 3 — Verify and make it permanent

free -h
swapon --show

Swap is live but would vanish at reboot. Persist it in /etc/fstab:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Verifying active swap with free and swapon --show and persisting in fstab on Ubuntu

Step 4 — Tune swappiness for a server

vm.swappiness (0–100, default 60) controls how eagerly the kernel swaps. Desktops like 60; on servers you want RAM used for real work and swap kept for emergencies:

sudo sysctl vm.swappiness=10
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf

Removing or resizing swap

sudo swapoff /swapfile
sudo rm /swapfile         # then recreate at the new size
# and remove/adjust the /etc/fstab line

Frequently asked questions

Is swap bad for SSDs?

Modern SSD endurance makes occasional swapping a non-issue. A server that is constantly swapping, though, has a memory problem swap cannot solve — check what is eating your RAM and consider upgrading the plan.

My VPS feels slow since adding swap — why?

Swap is orders of magnitude slower than RAM; heavy swap use means the working set no longer fits in memory. Swap prevents crashes; it does not add capacity. If free -h shows swap heavily used day-to-day, it is time for more RAM — our VPS plans scale in minutes.

Related Ubuntu guides

Prefer to have experts handle it?

LFA IT provides fully managed Ubuntu VPS and dedicated servers — initial setup, security hardening, monitoring and 24/7 support, so you can focus on your business. Explore our hosting and server management services or open a support ticket and our engineers will take it from there.


Was this answer helpful?

« Back