Skip to content
Mehdi Kababfrontend / author
⁠The notebook

Increase the size of the swap file

Ubuntu swaps into a single file, so doubling it takes five minutes: no repartitioning, no reboot, and a swappiness tweak keeps the kernel from using it too eagerly.

Ubuntu uses a swap file, /swap.img, not a swap partition. Growing it takes five minutes: no repartitioning, no reboot.

Resize the swap file

  1. Find the active swap file and its current size:

    shell
    $ swapon --show
    NAME      TYPE SIZE USED PRIO
    /swap.img file   8G   0B   -2
  2. Turn swap off. The kernel moves whatever is swapped out back into Random Access Memory (RAM), so first check with free -h that enough memory is available:

    shell
    $ sudo swapoff /swap.img
  3. Grow the file to 16 Gigabyte (GB):

    shell
    $ sudo fallocate -l 16G /swap.img
  4. Format it as swap again (the new size is ignored until you do):

    shell
    $ sudo mkswap /swap.img
  5. Turn swap back on:

    shell
    $ sudo swapon /swap.img
  6. Check the new size:

    shell
    $ swapon --show
    NAME      TYPE SIZE USED PRIO
    /swap.img file  16G   0B   -2

The path doesn’t change, so the existing /etc/fstab entry keeps working after a reboot.

Note

If swapon rejects the file because it “has holes”, your filesystem doesn’t support swap files made by fallocate. Create the file with dd instead:

shell
sudo dd if=/dev/zero of=/swap.img bs=1M count=16384 status=progress

On Btrfs, delete the file and recreate it with

shell
sudo btrfs filesystem mkswapfile --size 16G /swap.img

Tune how eagerly the kernel swaps

A bigger swap file doesn’t mean you want the kernel to use it more. Two settings control that:

shell
$ echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swap.conf
$ echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.d/99-swap.conf
$ sudo sysctl --system
  • vm.swappiness=10 (default 60): the kernel keeps application memory in RAM and only swaps under real memory pressure.
  • vm.vfs_cache_pressure=50 (default 100): the kernel keeps directory and inode caches longer, so file lookups stay fast.

The file in /etc/sysctl.d/ makes both settings survive a reboot, and sysctl --system applies them right away.