How to Create Swap Space in CentOS

How to Create Swap Space in CentOS, Redhat

Swap space is used to swap process pages in and out of memory when your server’s memory becomes full, or if a process has been inactive for too long. You can configure it as a separate swap file or disk partition. In this article, we will look at how to create swap space in CentOS, Redhat, Fedora Linux.


How to Create Swap Space in CentOS, Redhat

In every operating system, processes are loaded into memory (physical RAM) as pages, and run from that location. As users run more processes on your system, its memory is consumed. As it starts running out of memory, the operating system swaps out inactive processes from the physical memory to the swap space on your disk. They are loaded back only when they become active again. This frees up memory for more processes. Here are the steps to create swap space on your Linux system.


1. Create Swap File

Open terminal and run the following command to create swap space of 1Gb on your server.

$ sudo fallocate -l 1G /swapfile
OR
$ sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576


2. Set Root Permissions

Next, you need to modify the permission of this newly created swap file such that only root users are able to modify it.

$ sudo chmod 600 /swapfile


3. Assign Swap file as Swap Space

Run the following command to tell Linux to use the newly created file as swap space.

$ sudo mkswap /swapfile


4. Enable Swap File

Run the following command to enable swap file.

$ sudo swapon /swapfile

Please note, these changes will be lost on system reboot. To make these changes permanent, open /etc/fstab file in a text editor

$ sudo vi /etc/fstab

and add the following line to it.

/swapfile swap swap defaults 0 0

Save and close the file.

You can verify the swap space with either of the following commands.

$ sudo swapon --show
OR
$ sudo free -h


5. (Optional) Remove Swap File

If you want to remove the swap file, you need to reverse the above steps in reverse order. First, you need to deactivate the swap file with the following swapoff command.

$ sudo swapoff -v /swapfile

Next, open /etc/fstab file and remove the following line from it.

/swapfile swap swap defaults 0 0

Save and close the file.

Finally, delete the actual swap file created in first step at the beginning of this article.

$ sudo rm /swapfile

This will disable and remove the swap space completely.

In this article, we have learnt how to create as well as remove swap file in Redhat, CentOS Linux.

Also read:

How to Install RPM Package in Redhat, CentOS
How to Configure Firewalld in Redhat, CentOS
How to Restart Linux Server from Command Line
How to Flush DNS Cache in Windows, Linux & Mac
How to Change Host Name in Debian/Ubuntu

Leave a Reply

Your email address will not be published. Required fields are marked *