Before continuing with this tutorial, 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.
NAME TYPE SIZE USED PRIO /swapfile file 1024M 0B -2
Although possible, it is not common to have multiple swap spaces on a single machine.
Creating a Swap File
The user you are logged in as must have sudo privileges to be able to activate swap. In this guide, we will add 1G of swap, if you want to add more swap, replace 1G with the size of the swap space you need.
Perform the steps below to add swap space on Ubuntu 18.04.
01. Start by creating a file which will be used for swap:
sudo fallocate -l 1G /swapfile
If fallocate is not installed or you get an error message saying fallocate failed: Operation not supported then use the following command to create the swap file:
02. Only the root user should be able to write and read the swap file. Set the correct permissions by typing:
sudo chmod 600 /swapfile
03. Use the mkswap utility to set up a Linux swap area on the file:
03. 格式化文件，若遗漏，则后续步骤会提示 invalid header
sudo mkswap /swapfile
04. 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
/swapfile swap swap defaults 0 0
05. Verify that the swap is active by using either the swapon or the free command as shown below:
sudo swapon --show
sudo free -h
Adjusting 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.