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.
- Lire cet article en français
- English
Ubuntu uses a swap file, /swap.img, not a swap partition. Growing it takes five minutes: no repartitioning, no reboot.
Resize the swap file
-
Find the active swap file and its current size:
shell$ swapon --show NAME TYPE SIZE USED PRIO /swap.img file 8G 0B -2 -
Turn swap off. The kernel moves whatever is swapped out back into Random Access Memory (RAM), so first check with
free -hthat enough memory is available:shell$ sudo swapoff /swap.img -
Grow the file to 16 Gigabyte (GB):
shell$ sudo fallocate -l 16G /swap.img -
Format it as swap again (the new size is ignored until you do):
shell$ sudo mkswap /swap.img -
Turn swap back on:
shell$ sudo swapon /swap.img -
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:
sudo dd if=/dev/zero of=/swap.img bs=1M count=16384 status=progressOn Btrfs, delete the file and recreate it with
sudo btrfs filesystem mkswapfile --size 16G /swap.imgTune how eagerly the kernel swaps
A bigger swap file doesn’t mean you want the kernel to use it more. Two settings control that:
$ 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 --systemvm.swappiness=10(default60): the kernel keeps application memory in RAM and only swaps under real memory pressure.vm.vfs_cache_pressure=50(default100): 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.
