As you all know, when the Linux system is consuming physical memory, the inactive pages are moved from physical memory to the SWAP space, and the SWAP space can exist as a dedicated SWAP partition or SWAP file. In most cases, the SWAP swap partition is not automatically created when running a Ubuntu system in a virtual machine.
The following I will introduce you how to manually create a SWAP partition for Ubuntu. Before you start creating, use the following command to check if your Ubuntu system has SWAP partitioning enabled:
sudo swapon –show
If the output is empty, it means that the current system has not enabled SWAP space; otherwise, you will see relevant feedback.
Create a SWAP partition
You can add a SWAP swap file to your Ubuntu 18.04.3 LTS system by performing the following steps:
Create a file for a swap with the following command: sudo fallocate -l 1G /swapfile
If fallocate is not installed or you receive an error, you can also create a swap file with the following command:
Execute the following command to set the correct permissions for the swapfile file:
sudo chmod 600 /swapfile
Use the mkswap utility to set up a Linux SWAP zone on a file:
sudo mkswap /swapfile
Activate the swap file with the following command:
sudo swapon /swapfile
To make the created swap partition permanent, you can write the contents of the swapfile path to the /etc/fstab file:
/swapfile swap swap defaults 0 0
Use the swapon or free command to verify that SWAP is active, as follows:
sudo swapon –show sudo free -h
Adjust the Swappiness value
Swappiness is a Linux kernel property that defines how often Linux systems use SWAP space. Swappiness values can range from 0 to 100. Lower values will allow the kernel to use SWAP space as little as possible, while higher values will allow the Linux Kernel to use SWAP partitions more aggressively.
The default Swappiness value is 60 in Ubuntu 18.04.3, you can use the following command to view:
A value of 60 is still a good idea for Ubuntu 18.04.3 desktop, but for Ubuntu Server, SWAP is used more frequently, so you may need to set a lower value. For example, to set the swappiness value to 40, execute:
sudo sysctl vm.swappiness=40
If you want the settings to remain valid after the system is restarted, you will need to add the following to the /etc/sysctl.conf file:
The optimal swappiness value depends on the workload of your system and how memory is used. You should adjust this parameter in small increments to find the best value.
Remove SWAP partition
In Ubuntu 18.04.3 to deactivate and delete a SWAP file, follow these steps
First, disable the SWAP space by entering the following command:
sudo swapoff -v /swapfile
Delete the line of valid swap in the /etc/fstab file.
Finally, execute the following command to delete the swapfile file: