A swap file is the simple alternative to a swap partition: it can be created, enlarged or removed at any time without repartitioning the disk. Especially on small VPSs or virtual machines with little RAM, a swap file prevents processes from being killed by the OOM killer during load peaks.
Is there swap already?
swapon --show
free -h
Ubuntu usually creates /swap.img during installation already. If swapon --show prints nothing, no swap is active.
Creating a swap file (ext4, XFS)
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
fallocatereserves the 2 GB immediately without writing to them.chmod 600is important: passwords and other sensitive data can end up in swap.mkswapformats the file as swap space,swaponactivates it.
If swapon reports an error such as “Invalid argument” (which happens on some file systems), create the file with dd instead:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
Special case: Btrfs
On Btrfs (e.g. Fedora or openSUSE) the file must be created without copy-on-write. Current Btrfs tools do this in a single step:
sudo btrfs filesystem mkswapfile --size 2G /swapfile
sudo swapon /swapfile
Enabling it permanently
For the swap file to be active again after a reboot, add a line to /etc/fstab:
/swapfile none swap sw 0 0
A typo in fstab can prevent the system from booting. So test before rebooting: sudo swapoff /swapfile && sudo swapon -a && swapon --show
Enlarging the swap file
sudo swapoff /swapfile
sudo fallocate -l 4G /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
When swap is switched off, the swapped-out data is moved back into memory. If there is not enough free RAM for that, swapoff fails – in that case create a second swap file temporarily.
Setting the swappiness
The value vm.swappiness (0–200, default 60) determines how early the kernel starts swapping. For servers and desktops with sufficient RAM a low value makes sense:
cat /proc/sys/vm/swappiness
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system
How large should the swap file be?
- Up to 2 GB RAM: about twice as much swap as RAM
- 2–8 GB RAM: about as much as RAM
- More than 8 GB RAM: 2–4 GB as a safety buffer
- With hibernation: at least as large as the RAM
Removing the swap file again
sudo swapoff /swapfile
sudo rm /swapfile
# then delete the line in /etc/fstab
Whether and how heavily the system is swapping is easy to watch with htop (the “Swp” bar).
Originally published in 2009, completely revised in November 2026.