How to Create or Remove SWAP File in Centos 7

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

[[email protected] ~]# free -m

total used free shared buff/cache available

Mem: 1790 75 331 1 1383 1540

Swap: 000

If Swap shows 0s, then swap isnt configured.

Alternatively, use the swapon command

[[email protected] ~]# swapon --show

Empty output means swap isn’t configured.

2. Create the swap file

[[email protected] ~]#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

[[email protected] ~]#dd if=/dev/zero of=/swapfile bs=1024 count=4194304

3. Give only root user read/write permissions to the swap file

[[email protected] ~]# chmod 600 /swapfile

4. Setup swap area

[[email protected] ~]# mkswap /swapfile

5. Activate the swap memory

[[email protected] ~]# swapon /swapfile 

6. Open /etc/fstab using your favourite editor and copy the code below in it:

[[email protected] ~]# 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

[[email protected] ~]# 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

[[email protected] ~]# swapon --show
NAME      TYPE  SIZE   USED PRIO
/swapfile file 1024M 178.4M   -2

Removing Swap File

1. Deactivate swap space first

[[email protected] ~]# 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

 [[email protected] ~]# rm -f /swapfile

Leave a Reply

Your email address will not be published.