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
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#
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#
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/fstabCheck the result and confirm that fstab is valid.
swapon --show
sudo findmnt --verifyHow 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#
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --systemSee whether the server leans on swap#
vmstat 1 5If 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#
sudo swapoff /swapfile
sudo sed -i '\|^/swapfile |d' /etc/fstab
sudo rm /swapfileFrequently 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.