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 -hshows 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
- Install Docker and Compose on Ubuntu 24.04Install Docker Engine and the Compose plugin from the official repository, run it as a normal user and avoid the UFW bypass.
- Set up a UFW firewall on Ubuntu 24.04Enable UFW with safe defaults, allow only the ports you use, rate-limit SSH, restrict access by IP and remove rules.
- Back up your server with resticEncrypted, deduplicated backups of your VPS to a server you control: install restic, run the first backup, schedule it and test a restore.
- Create an encrypted volume with LUKSKeep sensitive files in a LUKS-encrypted volume on a single-disk VPS: create, open, close, and what it does and does not protect.
