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.
Close the file access rights for everyone except root.
Configure the swap area in the /swap file.
Output:
no label, UUID=3c2ac0c0-3cc2-4571-b072-5f7d556acc88
Activate the swap file.
To activate it after a reboot, open the file:
Paste this line at the end of it.
Checking the swap file
To see the size and used space of the swap file use the command:
Output:
/swap file 4G 0B -2
The second option is to view the state of RAM and the swap file.
Output:
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:
Output:
To set it to 20 use the following command or enter a value from 0 to 100:
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.
Then remove this line from the /etc/fstab file.
Finally, delete the file from the file system.