Increase Swap Space on Almalinux or CentOS Print

  • VPS Admin Management
  • 2

Swap space in Linux is used when the amount of physical memory (RAM) is full. If the system needs more memory resources and the RAM is full, inactive pages in memory are moved to the swap space.

Without swap space, the kernel will kill high memory usage processes to maintain system stability.  The first process on the list is usually MySQL even though it may not be the cause of the memory spike.

You can modify the swap size without rebooting your server.

How to modify the swap file size

  • 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
/swapfile swap swap defaults        0 0


Based on the last line, our swap file is located at /swapfile

  • Turn off this swap file:
    swapoff /swapfile

    This can take a while if the current swap is quite large and the OS manages the change.
    Use free -m to monitor

  • Remove the old swap file:
    rm -f /swapfile

  • Make sure you have enough drive space for your new swap file:
    df -h

  • Create a new swap file (the size is 8GB in this example: 8192 x 1Mib):
    dd if=/dev/zero of=/swapfile count=8192 bs=1MiB

  • Make this file as a swap file:
    mkswap /swapfile

  • Set right permission:
    chmod 600 /swapfile

  • Turn the swap on again:
    swapon /swapfile

  • Confirm memory usage:
    free -m

Was this answer helpful?

« Back