Create permanent swap space in Centos 7

Carvia Tech | May 08, 2020 | 2 min read | 14 views


In this article, we will add file system based additional memory on Centos 7 operating system using swap file.

Steps to add permanent swap space in Centos 7

1. Check if swap space is already enabled

$ sudo swapon -s

If swap space is already active, the above command will output information about swap

Output
NAME      TYPE  SIZE   USED PRIO
/swapfile file 1024M 507.4M   -1

2. Create a file which will be used as swap space:

$ sudo fallocate -l 4G /swapfile

this will allocate 4GB of disc space to swapfile.

3. Set correct permissions on this file to only allow root user

We want to ensure that only root user can read and write to this newly created swap file.

$ sudo chmod 600 /swapfile

4. Setup this file as linux swap file

$ sudo mkswap /swapfile

5. Activate the swap space

$ sudo swapon /swapfile

After this command you should be able to see the swap swpace in overall computer memory. Check it using below command.

$ sudo free -h

or the below command:

$ sudo swapon --show

6. Make swap permanent

By default this swap file will go away after you rebootyour system. To persist changes across reboots, you need to add the swap entry into /etc/fstab file.

$ sudo vi /etc/fstab

And paste the below line:

/etc/fstab
/swapfile swap swap defaults 0 0

7. Adjust system swappiness value

Swappiness value defines at what priority the swap space will be used by the operating system. Value can range from 0 (os avoids using swap) to 100 (os will aggressively use swap space). Default value of swap space could be around 30.

If you are using SSD, its better to keep system swappiness to a low value like 5 or 10 (so that lesser number of writes happen on swap)

$ cat /proc/sys/vm/swappiness
Output

30

$ sudo vi /etc/sysctl.conf

Add the below line:

/etc/sysctl.conf
vm.swappiness=10

8. Remove swap space completely

If you want to remove the swap space completely, you can follow these steps:

  1. Turn off the swap $ sudo swapoff -v /swapfile

  2. Remove swap file entry from /etc/fstab which contains /swapfile swap swap defaults 0 0

  3. Delete the actual swap file on system using sudo rm /swapfile

That’s all.


Top articles in this category:
  1. DevOps interview questions - Basic Concepts, Microservices, Databases, AWS
  2. Basic Unix commands for every programmer
  3. Install ElasticSearch 7 on Ubuntu 18.04
  4. Install and upgrade Jenkins on Ubuntu 18.04 LTS
  5. Upgrade MySQL from 5.7 to 8 on Ubuntu 18.04
  6. Installing nginx on macOS Mojave using brew
  7. Scp to send & receive files on unix


Find more on this topic:
Dev Ops image
Dev Ops

Dev Ops Automation - Ubuntu OS, Centos, MySql, MongoDB, Java, AWS Infrastructure.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info