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

bash
swapon --show
free -h

If 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.

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

Don'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:

bash
echo '/swapfile none swap sw 0 0' >> /etc/fstab

Then check the line went in once, not twice (easy to do if you ran it again):

bash
grep swapfile /etc/fstab

Tell 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:

bash
sysctl vm.swappiness=10
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swappiness.conf

The first line changes it now. The file makes it stick.

Check both:

bash
swapon --show
cat /proc/sys/vm/swappiness

You want to see /swapfile at 2G, and 10. Reboot once and check again, just to be sure it all survives.

Removing or resizing it

bash
swapoff /swapfile
sed -i '/^\/swapfile /d' /etc/fstab
rm /swapfile

To 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 the chmod anyway.
  • read swap header failed: the file was never formatted. Run mkswap /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.

Be first when orders open

Join the waitlist and we'll send you one email when VPSNine launches. Pick a plan if you already know which one you want, and we'll size the first servers around it.