Swap (swap memory) is a space on the hard disk. When the physical memory is exhausted, the swap memory will be used. When a Linux system is running low on memory, inactive memory pages will be moved from RAM space to Swap memory swap space.
Swap space may exist in the form of an independent memory swap partition or a swap file. Usually, running CentOS on a virtual machine does not have an existing memory swap partition, so the only option is to create a swap file.
This article will describe several steps to add a swap file to CentOS 8 system.
Perform the following steps as root or another user with sudo privileges to add swap space on CentOS 8 system.
sudo fallocate -l 1G /swapfile
In this example, we created a swap file with a size of 1G. If you need more memory swap space, replace 1G
with the size you want.
If fallocate
is not available on your system, or you get an error message: fallocate failed: Operation not supported
, use the dd
command to create a swap file.
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
sudo chmod 600/swapfile
sudo mkswap /swapfile
Setting up swapspace version 1, size =1024MiB(1073737728 bytes)
no label, UUID=0abdb8ba-57d6-4435-8fd8-5db9fc705045
sudo swapon /swapfile
swapon
or free
command to verify whether the swap space has been activated, like the following:sudo swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 1024M 507.4M -1
sudo free -h
total used free shared buff/cache available
Mem: 488M 158M 83M 2.3M 246M 217M
Swap:1.0G 506M 517M
/etc/fstab
file.sudo nano /etc/fstab
Paste the following content into the back of the file:
/swapfile swap swap defaults 00
Swappiness is a Linux Kernel attribute value, which defines how often the system uses swap space. The value of Swappiness ranges from 0 to 100. A lower value makes the kernel avoid using swap memory as much as possible, while a higher value makes the kernel use swap memory as much as possible.
The default value of swappiness on CentOS 8 is 30. You can check the current swappiness value by typing the following command:
cat /proc/sys/vm/swappiness
30
When the swappiness value is 30, it is suitable for desktop and development machines. For production servers, you may need to lower this value. For example, to lower the swappiness value to 10, enter:
sudo sysctl vm.swappiness=10
To persist this parameter, you should paste the following content into the /etc/sysctl.conf
file, and restart:
vm.swappiness=10
The optimal swappiness value depends on the workload of your system and how your memory is used. You should increase the value of this parameter little by little to find the optimal value.
To deactivate and remove the swap file, follow these steps:
sudo swapoff -v /swapfile
Remove the swap entry /swapfile swap swap defaults 0 0
from the /etc/fstab
file.
Use rm
to delete the actual swap file:
sudo rm /swapfile
We have demonstrated to you how to create a swap file on CentOS 8, and activate and configure the swap space.
Recommended Posts