How to Add Swap Space on Ubuntu 20.04

Swap is an additional space to the amount of RAM allocated from the hard disk space. If there is not enough RAM, the system moves the oldest data to the swap, thereby freeing up space for active applications.

Recommendations for the swap file

Hard drives, even solid-state drives, are slower than RAM. Thus, while designing and using the system, it is necessary to allocate the amount of RAM with a certain margin, leaving for the swap file the role of a backup space. The optimal swap size is equal to the amount of RAM, but in some cases it can be doubled.
Virtual servers are usually devoid of a swap space. On physical servers, it is usually set automatically, but can be changed for some purposes. In this tutorial, we will create a 4 GB swap file.

Swap file creation

First, let’s create a file and preallocate space for the swap.

sudo fallocate -l 4G /swap

Close the file access rights for everyone except root.

sudo chmod 600 /swap

Configure the swap area in the /swap file.

sudo mkswap /swap

Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
no label, UUID=3c2ac0c0-3cc2-4571-b072-5f7d556acc88

Activate the swap file.

sudo swapon /swap

To activate it after a reboot, open the file:

sudo nano /etc/fstab

Paste this line at the end of it.

/swap swap swap defaults 0 0

Checking the swap file

To see the size and used space of the swap file use the command:

sudo swapon --show

/swap file 4G 0B -2

The second option is to view the state of RAM and the swap file.

sudo free -h

total used free shared buff/cache available
Mem: 1.9Gi 74Mi 1.8Gi 0.0Ki 115Mi 1.7Gi
Swap: 4.0Gi 0B 4.0Gi

Swappiness set up

Swappiness is a parameter that allows you to adjust the level of swap usage by the system. A high value will result in active use of the swap file, while a low value will result in minimal use.
To see the current value, enter:

cat /proc/sys/vm/swappiness


To set it to 20 use the following command or enter a value from 0 to 100:

sudo sysctl vm.swappiness=20

To save this setting after a reboot, open the /etc/sysctl.conf file and insert it there:


Save it and close.

Removing the swap file

First, deactivate the swap file.

sudo swapoff /swap

Then remove this line from the /etc/fstab file.

/swap swap swap defaults 0 0

Finally, delete the file from the file system.

sudo rm /swap