A swap file lets the kernel move idle pages out of RAM onto disk. It’s handy on small-memory hosts (VPS, VMs) that have no dedicated swap partition, and unlike a partition it can be resized or removed without repartitioning.

Create the swap file

1
2
3
4
5
6
7
# Allocate a 1 GiB file. dd is preferred over fallocate here because
# swapon rejects files with holes on some filesystems (e.g. ext4, XFS).
dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress

chmod 0600 /swapfile   # only root may read/write the swap file
mkswap /swapfile       # format it as swap space
swapon /swapfile       # enable it immediately

Make it persistent

Add an entry to /etc/fstab so the swap file is mounted on every boot. The grep guard keeps this idempotent — running it twice won’t add a duplicate line.

1
grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap defaults 0 0' >> /etc/fstab

Tune swappiness

vm.swappiness (0–100, default 60) controls how aggressively the kernel swaps; a lower value keeps more data in RAM. 10 is a common choice for servers.

Write it to a drop-in file under /etc/sysctl.d/ rather than editing /etc/sysctl.conf directly with >, which would overwrite the whole file and wipe any existing settings.

1
2
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swappiness.conf
sysctl --system   # reload all sysctl.d drop-ins

Verify

1
2
swapon --show
free -h