Monday, August 14, 2023

How to create swap file in Linux | How to increase swap partition in RHEL/CentOS

 To create a swap file in Red Hat Enterprise Linux 8 (RHEL 8) or any other
  Linux 
distribution, you can follow these steps:

  • Check Current Swap Usage (Optional): Before creating a new swap file, you might want to check your current swap usage. You can use the free or swapon command to do this:
    bash

    free -h 

    swapon -s

  • Determine Swap File Size: Decide on the size of the swap file you want to create. The size of the swap file depends on factors such as the amount of RAM you have and your specific needs. A common recommendation is to set the swap size to be equal to or slightly larger than your system's RAM.

  • Create the Swap File: Open a terminal and use the following commands to create a swap file. Replace <swapfile_path> with the actual path where you want to create the swap file (e.g., /mnt/swapfile), and <swapfile_size> with the desired size in megabytes (e.g., 2048M for 2GB):
    bash
     
    dd if=/dev/zero of=<swapfile_path> bs=1M count=<swapfile_size>

    Example:

    dd if=/dev/zero of=/mnt/swapfile bs=1M count=2048

  • Adjust Permissions: Set appropriate permissions on the swap file to ensure it's accessible only by the root user:
    bash

    sudo chmod 600 <swapfile_path>

    Example:

    sudo chmod 600 /mnt/swapfile

  • Configure the Swap File: Set up the swap file using the mkswap command:
    bash

    sudo mkswap <swapfile_path>

    Example:

    sudo mkswap /mnt/swapfile

  • Enable the Swap File: Activate the swap file using the swapon command:
    bash

    sudo swapon <swapfile_path>

    Example:

    sudo swapon /mnt/swapfile

  • Make Swap Permanent (Optional): To ensure that the swap file is enabled after system reboots, you need to add an entry to the /etc/fstab file. Open the file in a text editor:
    bash

    sudo nano /etc/fstab


    Add the following line to the file, where <swapfile_path> is the path of your swap file:
    php

    <swapfile_path> swap swap defaults 0 0

    Example:

    /mnt/swapfile swap swap defaults 0 0


    Save and close the file.

  • Verify Swap: You can verify that the swap file is being used by checking the output of the free or swapon command again:
    bash

    free -h

    swapon -s

That's it! You have successfully created a swap file on your Red Hat Enterprise Linux 8 or any Linux flavoured system. Remember that using swap space can impact performance, so it's recommended to have an appropriate balance of RAM and swap based on your system's needs.

No comments:

Post a Comment

Installing Jenkins on RHEL 8 is a straightforward process. Here's a step-by-step guide

Introduction  Jenkins is an open-source automation server widely used for continuous integration (CI) and continuous delivery (CD) pipelines...