How to Add Swap Space on Ubuntu 20.04
- Systems with less than 2 GB RAM – 2 times the amount of RAM.
- Systems with 2 to 8 GB RAM – the same size as the amount of RAM.
- Systems with more than 8 GB RAM – at least 4 GB of Swap
First, create a file that will be used as swap:
sudo fallocate -l 2G /swapfile
If the fallocate
the utility is not present on your system, or you get an error message saying fallocate failed: Operation not supported
, use the following command to create the swap file:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152
Set the file permissions to 600
to prevent regular users to write and read the file:
sudo chmod 600 /swapfile
Create a Linux swap area on the file:
sudo mkswap /swapfile
Activate the swap file by running the following command:
sudo swapon /swapfile
To make the change permanent open the /etc/fstab
file:
sudo nano /etc/fstab
and paste the following line:
/swapfile swap swap defaults 0 0
Verify that the swap is active
sudo swapon --show
Swappiness is a Linux kernel property that defines how often the system will use the swap space. It 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.
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.
For example, to set the swappiness value to 10
, run:
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
The optimal swappiness value depends on your system workload and how the memory is being used. You should adjust this parameter in small increments to find an optimal value.
Leave a Comment