›INDEX
Last Updated:

Swapfile

Swap is a space on disk that is used when the amount of physical RAM memory is full. When a Linux system runs out of RAM, inactive pages are moved from the RAM to the swap space.

Advantages of swapfile over swap partition

  • If the main drive is encrypted with LUKS, the swap partition would have to be encrypted separately, whereas a swapfile is a part of the root directory.
  • It's easier to resize a swapfile rather than a swap partition.

Creation

  • Create a file that will be used for swap
sudo fallocate -l 1G /swapfile

Alternative:

sudo dd if=/dev/zero of=/swapfile bs=1G count=8
  • Only the root user should be able to write and read to the swap file
sudo chmod 600 /swapfile
  • Use the mkswap utility to set up the file as linux swap area
sudo mkswap /swapfile
  • Enable swap
sudo swapon /swapfile

To permanently enable swap on boot you need to add the following line to /etc/fstab file.

/swapfile swap swap defaults,noatime 0 0
  • To verify that the swap is active you can use one of the two commands, free or swapon
sudo swapon --show
sudo free -h

Adjust of swappiness value

Swappiness is the Linux kernel property that defines how often the system will use the swap space. Swappiness can have a value between 0 and 100. A low value will make the kernel try to avoid swapping whenever possible, while a higher value will make the kernel use the swap space more aggressively.

The default swappiness value is 60.

  • Check swappiness value
cat /proc/sys/vm/swappiness
  • Change swappiness
sudo sysctl vm.swappiness=10

To make it persistent across reboots append the following line to the /etc/sysctl.conf file:

vm.swappiness=10

Increase swap size

sudo swapoff -a
sudo dd if=/dev/zero of=/swapfile bs=1G count=16
sudo mkswap /swapfile
sudo swapon /swapfile

Enjoy the notes on this website? Consider supporting me in this adventure in you preferred way: Support me.