Add a swap file
Create a swap file on Ubuntu 24.04 or Debian 12, make it permanent, and tune swappiness so it is used only when needed.
Swap is disk space the kernel borrows when RAM runs out. It's far slower than RAM, but it turns a sudden out-of-memory kill into a short slowdown, which is much easier to recover from. On a server with 2 to 4 GB of RAM, a swap file the size of the RAM (up to 2 GB) is a good start.
See if you already have some
swapon --show
free -hIf swapon --show prints nothing, there's no swap yet. If it lists one, you can stop here, or jump to the end to resize it.
Create the file
This makes a 2 GB file at /swapfile. Change 2G if you want a different size.
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfileDon't skip the chmod 600. Swap can hold anything that was in memory, passwords included, so only root should be able to read it.
fallocate works on ext4, which is what you'll almost certainly have. If it says Operation not supported, use dd if=/dev/zero of=/swapfile bs=1M count=2048 instead and carry on from chmod.
Keep it after a reboot
Right now swap is on, but only until the next boot. Add it to /etc/fstab:
echo '/swapfile none swap sw 0 0' >> /etc/fstabThen check the line went in once, not twice (easy to do if you ran it again):
grep swapfile /etc/fstabTell the kernel to go easy on it
vm.swappiness is how keen the kernel is to move memory out to swap. The default is 60. On a server, 10 keeps your busy programs in RAM and leaves swap for emergencies:
sysctl vm.swappiness=10
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swappiness.confThe first line changes it now. The file makes it stick.
Check both:
swapon --show
cat /proc/sys/vm/swappinessYou want to see /swapfile at 2G, and 10. Reboot once and check again, just to be sure it all survives.
Removing or resizing it
swapoff /swapfile
sed -i '/^\/swapfile /d' /etc/fstab
rm /swapfileTo resize, remove it like that and create it again at the new size. swapoff needs enough free RAM to take back what's in swap, so if it fails, stop a service or two first.
A few messages you might meet:
insecure permissions 0644, fix with: chmod 0600 /swapfile: just a warning, swap is on. Run thechmodanyway.read swap header failed: the file was never formatted. Runmkswap /swapfile.
And if swap is always full and the server crawls, swap is hiding a real memory shortage. Find the culprit with top (press M to sort by memory), or move to a bigger plan.