Resize swap memory size on CentOS 7 without reboot

Resize swap memory size on CentOS 7 without reboot

Sometimes we have to resize the swap size. Possible reasons:

  1. Running out of memory
    1. You have to increase the swap size
    2. Check the storage. Do you have enough free disk space to extend the swap file?
    3. Check the current memory usage by running top command to determine which process uses a lot of memory. May you don't have to increase the memory :)

  2. Running out of disk space
    1. One possible solution is to decrease the swap size
    2. Check that you have enough memory by running free -m command
    3. Check that the swap partition and the small partition are in the same place? If not, may this change is useless in your case.

 

Let's see how to modify the swap size on CentOS 7

 

  • Check the current size of the swap:

    free -m


  • Check the current swap file location:

    cat /etc/fstab
# Accessiblefilesystems, byreference, aremaintainedunder '/dev/disk'
# See man pagesfstab(5), findfs(8), mount(8) and/orblkid(8) for more info
#
/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
/dev/mapper/centos-swap swap swap defaults        0 0


Based on the last line, our swap file located at /dev/mapper/centos-swap

 

  • Turn off this swap file:

    swapoff /dev/mapper/centos-swap


  • Remove the old swap file:

    rm -f /dev/mapper/centos-swap


  • Create a new swap file (the size is 8GB in this example):

    dd if=/dev/zero of=/dev/mapper/centos-swap count=8192 bs=1MiB


  • Make this file as a swap file:

    mkswap /dev/mapper/centos-swap


  • Set right permission:

    chmod 600 /dev/mapper/centos-swap


  • Turn the swap on again:

    swapon /dev/mapper/centos-swap


  • Check what we did:

    free -m

Comments