How to Add Swap Space on CentOS 7:
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 take the form of either a dedicated swap partition or a swap file. In most cases when running CentOS on a virtual machine a swap partition is not present so the only second option is to create a swap file.
You can follow below step to add a swap file on CentOS 7 systems
Before proceeding with this following step, check if your CentOS 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.
Output NAME TYPE SIZE USED PRIO /dev/dm-1 partition 1.5G 0B -1
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.
Follow the steps below to add swap space on a CentOS 7 system.
First, create a file which will be used as swap space:
$ sudo fallocate -l 1G /swapfile
fallocate utility is not available 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=1048576
Ensure that only the root user can read and write the swap file by setting the correct permissions :
$ sudo chmod 600 /swapfile
Next, set up a Linux swap area on the file:
$ sudo mkswap /swapfile
Run the following command to activate the swap:
$ sudo swapon /swapfile
Make the change permanent by opening the
$ sudo nano /etc/fstab
and pasting the following line:
/etc/fstab /swapfile swap swap defaults 0 0
$ sudo swapon --show
Output NAME TYPE SIZE USED PRIO /swapfile file 1024M 507.4M -1
$ sudo free -h
Output total used free shared buff/cache available Mem: 488M 158M 83M 2.3M 246M 217M Swap: 1.0G 506M 517M
The default swappiness value on CentOS 7 is 30. You can check the current swappiness value by typing the following command:
$ cat /proc/sys/vm/swappiness
For example, to set the swappiness value to 10, type:
$ sudo sysctl vm.swappiness=10
To make this parameter persistent across reboots append the following line to the
Removing a Swap File:
Deactivating the swap space by typing:
$ sudo swapoff -v /swapfile
Next, remove the swap file entry
/swapfile swap swap defaults 0 0 from the
Finally, delete the actual swapfile file with
$ sudo rm /swapfile