User Tools

Site Tools


Swap Space Configuration

1.0 --- Check

First we check if your Ubuntu installation already has swap enabled by typing:

sudo swapon --show

If the output is empty, it means that your system does not have swap space enabled. Otherwise if you get something like below, you already have swap enabled on your machine:

/dev/sda2 partition 1.9G   0B   -2

1.1 --- Create Swap File

Start by creating a file which will be used for swap:

sudo fallocate -l 2G /swapfile

Only the root user should be able to write and read the swap file. Set the correct permissions by typing:

sudo chmod 600 /swapfile

Use the mkswap utility to set up a Linux swap area on the file:

sudo mkswap /swapfile

Activate the swap file using the following command:

sudo swapon /swapfile

To make the change permanent open the /etc/fstab file:

sudo nano /etc/fstab

and paste the following line:

/swapfile swap swap defaults 0 0

Verify that the swap is active by using either the swapon or the free command as shown below:

sudo swapon --show
/swapfile file 1024M 507.4M   -1

1.2 --- 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 OK for Desktops, for production servers you may need to set a lower value. To set the swappiness value to 20, type:

sudo sysctl vm.swappiness=20

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

sudo nano /etc/sysctl.conf

2.0 --- Removing Swap File

To deactivate and remove the swap file, follow these steps:

sudo swapoff -v /swapfile

Next, remove the swap file entry /swapfile swap swap defaults 0 0 from the /etc/fstab file.

Finally delete the actual swapfile file:

sudo rm /swapfile

x.x --- References

swap_space.txt · Last modified: 2019/02/02 22:52 by pi