Updated 1 min read

Add swap space on Ubuntu 24.04

Create a swap file on a small Ubuntu 24.04 VPS, make it permanent and tune swappiness so the server survives memory spikes.

Our servers come without swap. On a small plan, a memory spike makes the kernel kill your biggest process. A swap file is a safety net against that.

Note Swap is not extra RAM. It lives on a shared SSD, so a server that swaps all the time is slow. If free -h shows swap in constant use, move to a bigger plan.

Check what you have#

free -h
swapon --show

If swapon --show prints nothing, there is no swap.

Create the swap file#

For 2 GB of RAM, 2 GB of swap is a good size. Use 1G or 2G on bigger servers.

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Check it with swapon --show.

Make it permanent#

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Lower the swappiness#

The default of 60 moves memory to disk too eagerly. A server wants 10:

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

Confirm with cat /proc/sys/vm/swappiness.

Remove it later#

sudo swapoff /swapfile
sudo rm /swapfile

Then delete the /swapfile line from /etc/fstab.

Next: install Docker or review the initial server setup.

More in this section