Swap is a space on a disk that is used when the amount of physical RAM memory is full. When a Linux system runs out of RAM, inactive pages are moved from the RAM to the swap space.
Swap space can appear as either a committed swap partition or a swap file. Most of the time when running CentOS on a virtual machine a swap partition is absent so the only option is to make a swap file.
Below are the steps to enable SWAP file on CentOS 7.
Check if your CentOS installation already has swap enabled :
# swapon –show
The Output would be as below:
NAME TYPE SIZE USED PRIO
/dev/sda3 partition 4G 0B -1
If the output is null, it means that the server does not have swap space enabled.
In order to create SWAP file, the user you are logged in with should have sudo privileges or root access to the server.
Follow the steps below to add swap space on a CentOS 7 system.
Create a file which will be used as swap space:
# fallocate -l 8G /swapfile
You can replace the value 8G if you wish to add more swap space on server.
# chmod 600 /swapfile
Set up a Linux swap area on the file:
# mkswap /swapfile
To activate SWAP :
# swapon /swapfile
To make the change permanent, edit the /etc/fstab file:
# vi /etc/fstab
/swapfile swap swap defaults 0 0
Verify the swap is activated on server
# swapon –show
NAME TYPE SIZE USED PRIO
/swapfile file 8,192M 1055.8M -1
# free -h
total used free shared buff/cache available
Mem: 4096M 547M 3549M 2.3M 541M 874M
Swap: 8.0G 1055M 6845M
Adjust 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.
# cat /proc/sys/vm/swappiness
30
Set lower value on Production servers
# sysctl vm.swappiness=10
Also make the changes persistent after reboot:
# vi /etc/sysctl.conf
vm.swappiness=10
# sysctl -p