Beginner

How to add swap on Ubuntu when RAM runs short

Create a swapfile, keep it after reboot, and know when to add RAM instead

On this page
  1. Check whether you already have swap
  2. Add 2 GB of swap
  3. How much swap you need
  4. Stop the server from swapping too eagerly
  5. See whether the server leans on swap
  6. Remove swap
  7. Frequently asked questions

Swap is disk space Linux borrows when RAM fills up, so programs are not killed with an out-of-memory error. It is far slower than RAM, so treat it as a buffer for short spikes, not a replacement for more memory.

Check whether you already have swap#

Terminal
swapon --show
free -h
df -h /

If swapon --show prints nothing, there is no swap yet. Make sure the disk has room for the file you are about to create.

Add 2 GB of swap#

Terminal
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Check the result and confirm that fstab is valid.

Terminal
swapon --show
sudo findmnt --verify

How much swap you need#

RAM Starting swap size
1-2 GB Same as RAM
4 GB 2 GB
8 GB or more 2-4 GB to absorb spikes

Stop the server from swapping too eagerly#

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

See whether the server leans on swap#

Terminal
vmstat 1 5

If the si and so columns stay above zero during normal use, the server is constantly moving data between RAM and disk. That is the point to move to a plan with more RAM.

Remove swap#

Terminal
sudo swapoff /swapfile
sudo sed -i '\|^/swapfile |d' /etc/fstab
sudo rm /swapfile

Frequently asked questions#

Will adding swap slow my website down?

Not while it sits unused. If the server uses it constantly, pages get slower, but that is still better than the database being killed outright.

Do I need to reboot?

No. swapon takes effect immediately, and the fstab line brings swap back after every reboot.

Should Docker and databases use swap?

Swap is fine as a safety buffer, but size the database's memory settings to fit the real RAM.

Follow the guide on your own server

Create a Cloud Server with Ubuntu, Debian or Windows Server, billed by the hour in Thai baht. Support answers 24/7 in Thai and English.