The cart is empty

In the Linux operating system, including CentOS 7 distribution, swap space can be created either as a partition on the disk or as a swap file. In many cases, using a swap file can be advantageous, such as for its flexibility in allocating size without the need to change disk partitioning. This article provides a step-by-step guide on how to create and manage a swap file on a CentOS 7 system.

Prerequisites

Before proceeding, it's important that the system has enough free disk space to create a swap file of the desired size. It's commonly recommended to have a swap file size equal to or double the size of RAM, depending on your configuration and system needs.

Step 1: Creating a Swap File

  1. Open a terminal and enter the following command to create a swap file of size 4GB (adjust the number 4096 to the desired size in MB):

    sudo dd if=/dev/zero of=/swapfile bs=1M count=4096
    
  2. Set the correct permissions for the swap file to make it accessible only to the root user:

    sudo chmod 600 /swapfile
    

 

Step 2: Setting Up the Swap File

  1. Initialize the swap file with the following command:

    sudo mkswap /swapfile
    
  2. Activate the swap file using:

    sudo swapon /swapfile
    

 

Step 3: Ensure the Swap File is Used After Reboot

  1. Open the /etc/fstab file in an editor:

    sudo nano /etc/fstab
    
  2. Add the following line to the end of the file to automatically mount the swap file during system startup:

    /swapfile swap swap defaults 0 0
    
  3. Save and close the file.

 

Step 4: Configuring Swappiness

The swappiness value determines how aggressively the system uses swap space. Its value can be adjusted for system performance optimization.

  1. To check the current swappiness value, use:

    cat /proc/sys/vm/swappiness
    
  2. To set a new value, for example, 20, enter:

    sudo sysctl vm.swappiness=20
    
  3. For permanent changes, add the following line to the /etc/sysctl.conf file:

    vm.swappiness=20
    

Creating and managing a swap file on CentOS 7 is a straightforward process that can significantly enhance the flexibility and performance of your system. By following the provided steps, you ensure that your system efficiently utilizes swap space, which is particularly useful for systems with limited RAM.