How to Modify the Swap File Size on Linux (CentOS/RHEL)

Overview

This article explains how to safely resize a swap file on a Linux system (CentOS/RHEL-based).
The process involves disabling the existing swap file, removing it, creating a new swap file with the desired size, and re-enabling swap.

[!] Important:
Ensure the system has enough available disk space and sufficient free RAM before disabling swap to avoid performance issues.


Prerequisites

Before you begin, make sure you have:

    • Root or sudo access

    • Adequate free disk space

    • Sufficient physical memory to temporarily operate without swap


Step 1: Check the Current Swap Usage

Verify current memory and swap usage:

free -m

Step 2: Identify the Swap File Location

Check the system’s swap configuration:

cat /etc/fstab

Example output:

/dev/mapper/centos-root / xfs defaults        0 0
UUID=11bbb941-3929-44fc-89d5-94272765cb99 /boot xfs defaults        0 0
/dev/mapper/centos-home /home xfs defaults        0 0
/swapfile swap swap defaults        0 0

From the last line, the swap file is located at:

/swapfile

Step 3: Disable the Existing Swap File

Turn off swap:

swapoff /swapfile

[*] This may take some time if the swap file is large or heavily used.

Monitor progress:

free -m

Step 4: Remove the Old Swap File

Delete the existing swap file:

rm -f /swapfile

Step 5: Verify Available Disk Space

Ensure sufficient disk space for the new swap file:

df -h

Step 6: Create a New Swap File

Create a new swap file.
The example below creates an 8 GB swap file (8192 × 1 MiB):

dd if=/dev/zero of=/swapfile count=8192 bs=1MiB

[*] Adjust the count value to match your required swap size.


Step 7: Format the File as Swap

Mark the file as swap space:

mkswap /swapfile

Step 8: Secure the Swap File

Set correct permissions:

chmod 600 /swapfile

Step 9: Re-enable Swap

Activate the new swap file:

swapon /swapfile

Step 10: Confirm Swap Is Active

Verify memory and swap usage:

free -m

You should now see the updated swap size reflected in the output.


Notes & Best Practices

    • Keep swap size proportional to system RAM and workload

    • Avoid resizing swap on heavily loaded production systems during peak hours

    • Ensure /etc/fstab contains the correct swap entry for persistence after reboot


Summary

You have successfully resized the swap file by:

  1. Disabling swap

  2. Removing the old swap file

  3. Creating a new swap file

  4. Re-enabling swap

This approach ensures minimal disruption while safely adjusting swap capacity.

Was this answer helpful? 0 Users Found This Useful (0 Votes)