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.

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 /swapfile

Continue only if /swapfile does not exist. Do not overwrite an inactive existing file either.

Create and enable swap

  1. Create the file with restrictive permissions:

    sudo sh -c 'umask 077; dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress'
  2. Set permissions, initialise it and enable it:

    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
  3. 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/fstab

Add this entry only if /swapfile is not already configured:

/swapfile none swap sw 0 0

Save 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.swappiness

For example, to set it temporarily to 10:

sudo sysctl vm.swappiness=10

No 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 /swapfile

Continue only if it succeeds. Remove its /etc/fstab entry, then delete this specific file:

sudo rm /swapfile

Check swapon --show again. Never delete an active swap file.