Swap provides disk space that Linux can use to move some memory pages out of RAM. This guide explains how to add a 2 GiB swap file to Ubuntu 20.04 and retain it after a restart. Swap is slower than RAM and does not guarantee better application performance.
Ubuntu 20.04’s standard security maintenance ended in May 2025. Use appropriate Ubuntu Pro security maintenance or plan an upgrade to a supported release.
Before you begin
You need sudo access, enough free disk space and a filesystem supporting this swap-file procedure. Btrfs and some other configurations need a different setup; check the filesystem documentation.
Check active swap, memory and disk space:
swapon --show
free -h
df -h /No output from swapon --show means no active swap. Check for an existing file:
sudo ls -l /swapfileContinue only if /swapfile does not exist. Do not overwrite an inactive existing file either.
Create and enable swap
-
Create the file with restrictive permissions:
sudo sh -c 'umask 077; dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress' -
Set permissions, initialise it and enable it:
sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile -
Check the result:
swapon --show free -h
Stop and investigate any error before continuing.
Retain swap after a restart
Back up /etc/fstab, then open it:
sudoedit /etc/fstabAdd this entry only if /swapfile is not already configured:
/swapfile none swap sw 0 0Save and check carefully; incorrect entries can cause boot problems.
Optional: adjust swappiness
Swappiness influences how readily the kernel swaps memory pages. Check its current value:
sysctl vm.swappinessFor example, to set it temporarily to 10:
sudo sysctl vm.swappiness=10No value is best for every workload. To retain a chosen setting, edit an appropriate file under /etc/sysctl.d/ and check for duplicate or conflicting vm.swappiness settings.
Remove swap later
Ensure sufficient available RAM, then disable this file:
sudo swapoff /swapfileContinue only if it succeeds. Remove its /etc/fstab entry, then delete this specific file:
sudo rm /swapfileCheck swapon --show again. Never delete an active swap file.