Beta 42

Research and Development

Menu

Setup Swapfile on Linux Box

Swap is a space on a 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.

Swap space can take the form of either a dedicated swap partition or a swap file. In most cases, when running Linux on a virtual machine, a swap partition is not present, so the only option is to create a swap file.

This tutorial was tested on Linux systems with Ubuntu 18.04 and 19.10, but should also work with other Linux distributions as well.

sudo fallocate -l 1G /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Edit /etc/fstab and add: /swapfile swap swap defaults 0 0 at the end.

sudo mount -a

Adjust the Swappiness Value

Swappiness is a 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 to try to avoid swapping whenever possible, while a higher value will make the kernel to use the swap space more aggressively.

The default swappiness value is 60. You can check the current swappiness value by typing the following command:

cat /proc/sys/vm/swappiness

While the swappiness value of 60 is alright for most Linux systems, for production servers you may need to set a lower value.