Generally, the size of the swap file depends on how much RAM your system has:
- Less than 2 GB RAM – 2 times the amount of RAM.
- 2 to 8 GB RAM – the same size as the amount of RAM.
- More than 8 GB RAM – at least 4 GB of Swap.
Only root or user with sudo privileges can activate the swap file.
1). First, create a file that will be used as swap:
sudo fallocate -l 2G /swapfile
2). Set the file permissions to 600 to prevent regular users to write and read the file:
sudo chmod 600 /swapfile
3. Create a Linux swap area on the file:
sudo mkswap /swapfile
4). Activate the swap file by running the following command:
sudo swapon /swapfile
5). To make the change permanent open the /etc/fstab file:
sudo vi /etc/fstab
and paste the following line:
/swapfile swap swap defaults 0 0
6). Verify that the swap is active by using either the swapon or the free command, as shown below:
sudo swapon --show
and
sudo free -h
Adjusting the Swappiness Value
On Ubuntu, the default swappiness value is set to 60. You can check the current value by typing the following command:
cat /proc/sys/vm/swappiness
While the swappiness value of 60 is OK for most Linux systems, for production servers, you may need to set a lower value.
sudo sysctl vm.swappiness=10
To make this parameter persistent across reboots, append the following line to the /etc/sysctl.conf file:
vm.swappiness=10
Removing a Swap File
To deactivate and delete the swap file, follow these steps:
1). First, deactivate the swap space:
sudo swapoff -v /swapfile
2). Next, remove the swap file entry from the /etc/fstab file.
/swapfile swap swap defaults 0 0
3). Finally, remove the actual swapfile file using the rm command:
sudo rm /swapfile