Swap refers to disk space used when the RAM is full. Inactive pages in RAM are pushed to swap to free up some RAM space for current processes to use. Swap thus helps improve performance of a system. Swap can be configured as disk partition or as a file.
Lets have a look at how to configure swap file in centos7. We’ll configure 1GB swap in this tutorial.
1. Check if swap is already configured
[root@wm
~]# free -m
total
used free shared buff/cache available
Mem:
1790 75 331 1 1383
1540
Swap:
0
0
0
If Swap shows 0s, then swap isnt configured.
Alternatively, use the swapon command
[root@wm ~]#
swapon --show
Empty output means swap isn’t configured.
2. Create the swap file
[
root@wm
~]#
dd
if=/dev/zero of=/swapfile bs=1024 count=1048576
NOTE: If you would like to create a different sized swap file, say 4gb one, replace the count option. You can obtain the count by multiplying 1024 by the value you want in MBs eg 1024×4096 = 4194304. In my case then, the new command to create swap file is
[root@wm ~]#dd if=/dev/zero of=/swapfile bs=1024 count=4194304
3. Give only root user read/write permissions to the swap file
[root@wm ~]#
chmod 600 /swapfile
4. Setup swap area
[root@wm ~]#
mkswap /swapfile
5. Activate the swap memory
[root@wm ~]# swapon /swapfile
6. Open /etc/fstab using your favourite editor and copy the code below in it:
[root@wm ~]# vim /etc/fstab
/swapfile swap swap defaults 0 0
This makes the swap changes we’ve configured permanent
7. Verify that swap is active using free command
[root@wm ~]# free -m
total used free shared buff/cache available
Mem: 1790 75 331 1 1383 1540
Swap: 1023 178 84
or use the swapon command to verify
[root@wm ~]# swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 1024M 178.4M -2
Removing Swap File
1. Deactivate swap space first
[root@wm ~]# swapoff -v /swapfile
2. Remove the swap entry we had added in /etc/fstab. The entry was the line below
/swapfile swap swap defaults 0 0
3. Delete the actual swap file
[root@wm ~]# rm -f /swapfile