SoFunction
Updated on 2025-05-18

Two ways to increase Swap space in CentOS7

How to increase Swap space on CentOS 7

When the server does not have enough physical memory, increasing Swap space can be used as virtual memory to help the system handle memory pressure. Here are a few ways to increase Swap space:

Method 1: Create a new Swap file (recommended)

  • Check the current Swap usage:
free -h
swapon --show
  • Create files for Swap (for example, add 4GB):
sudo fallocate -l 4G /swapfile
  • iffallocateUnavailable, can be used:
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096
  • Set the correct permissions:
sudo chmod 600 /swapfile
  • Format the file to Swap:
sudo mkswap /swapfile
  • Enable Swap files:
sudo swapon /swapfile
  • Make the configuration permanently effective (automatically mount on the power supply):

Method 2: Adjust the Swap partition size (if there is LVM)

If using LVM, you can adjust the existing Swap partition:

  • Disable the current Swap:
sudo swapoff -v /dev/mapper/centos-swap
  • Resize the logical volume (for example, increase to 8GB):
sudo lvm lvresize /dev/mapper/centos-swap -L +4G
  • Reformat the Swap partition:
sudo mkswap /dev/mapper/centos-swap
  • Re-enable Swap:
sudo swapon -va

Optimize Swap usage

AdjustmentswappinessValue (0-100, indicating how much memory is used after starting to use Swap, default 60):

# Temporary settingssudo sysctl =30

# Permanent Settingsecho '=30' | sudo tee -a /etc/

Verify changes

free -h
swapon --show

Things to note

  • Swap space is located on the hard disk and is much slower than physical memory
  • For SSDs, frequent Swap operations may affect disk life
  • The ideal Swap size depends on the application scenario, and general recommendations:
    • Memory <2GB: Swap=2 times memory
    • Memory 2-8GB: Swap=equal to memory
    • Memory>8GB: Swap=0.5-1 times memory

This is the end of this article about two methods of increasing Swap space in CentOS7. For more related content on adding Swap space in CentOS7, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!