When CentOS servers run memory-intensive applications or handle sudden loads, physical memory can quickly run out, leading to sluggish system response, service anomalies, or even forced process termination. In such cases, expanding swap space becomes a crucial emergency measure to alleviate memory pressure and ensure system stability. Swap is a reserved space on the disk. When physical memory is insufficient, the operating system moves inactive pages from memory to swap, freeing up space for currently active processes.
Before deciding to expand swap, it's essential to confirm whether the system is truly facing memory pressure. The `free -h` command can quickly provide an overview of memory and swap usage, focusing on the "available" memory and "used" swap values. For more in-depth analysis, use the `vmstat 1` command to observe the "si" (swap-in from disk) and "so" (swap-out to disk) columns. If their values are consistently greater than 0, it indicates that the system is frequently using swap, and physical memory is strained. Another indicator is to use the `top` command to view the processes consuming the most memory. When available memory is nearing exhaustion and swap usage continues to increase, expanding swap is a direct and effective mitigation measure. However, it's important to understand that Swap essentially uses disk space to simulate memory, and its access speed is far lower than physical memory. Over-reliance on it can degrade overall system performance. Therefore, it's primarily used as a safety net when memory is exhausted, rather than a performance enhancement solution.
There are three main ways to add Swap on CentOS: creating a Swap file, creating a separate Swap partition, and using LVM logical volumes. Swap files are the most commonly used method due to their flexibility; they don't require repartitioning and can be created and adjusted directly on the existing file system, making them suitable for most scenarios. Separate Swap partitions offer slightly better performance but require adjusting the disk partition structure, which is complex and risky. LVM Swap volumes are suitable for systems already managed by LVM and can be adjusted online. For most users, creating a Swap file is the safest option.
The following is a detailed process for creating a Swap file on a CentOS 7/8 system. Assuming a 4GB Swap needs to be added, root privileges are required.
First, use the `dd` command to create an empty file of the specified size in the specified directory (usually `/` or `/var`). Command:
dd if=/dev/zero of=/swapfile bs=1M count=4096
Creates a file named `/swapfile` with a size of 4GB (4096 1MB blocks). `if=/dev/zero` means reading data from the zero device (filling with zeros), and `of` specifies the output file path. After creation, use `ls -lh /swapfile` to verify the file size is correct.
Next, set the correct file permissions to ensure only root can read and write. Execute `chmod 600 /swapfile`. Then, use the command `mkswap /swapfile` to format the file as swap space. This command will output a success message similar to the following:
Setting up swapspace version 1
After formatting, use:
swapon /swapfile
Immediately enable the new swap space. After enabling, execute again:
free -h
or
swapon --show
You should see the newly added swap space added to the total capacity and ready for use.
To ensure the system automatically mounts this swap file after a reboot, its information needs to be written to the `/etc/fstab` file. Add the following line to the end of the file:
/swapfile swap swap defaults 0 0
This line indicates that `/swapfile` will be used as a swap device with default parameters, meaning no checks or backups will be performed.
After creating the swap, adjusting its usage preferences can optimize system behavior. The `sysctl` parameter `vm.swappiness` controls the level of activity in which memory pages are swapped to disk. Its value ranges from 0 to 100, with higher values indicating more aggressive swapping. View the current value:
cat /proc/sys/vm/swappiness
The default value on CentOS is typically 30. For applications such as database servers that need to keep active data in memory as much as possible, it can be lowered to 10-20; for desktops or systems with severely limited memory, it can be increased to 60. Temporary adjustment:
sysctl vm.swappiness=20
For permanent effect, add `vm.swappiness=20` to `/etc/sysctl.conf` and then execute `sysctl -p`.
Another related parameter, `vm.vfs_cache_pressure`, controls the kernel's tendency to reclaim memory used for directory and inode caches; the default value is 100. Appropriately reducing this value (e.g., setting it to 50) allows the system to retain more cache, which is beneficial for file servers.
To resize an existing swap file, the procedure is: first, disable swap using `swapoff /swapfile`, then delete the original file (`rm /swapfile`) and recreate it at the new size, then re-execute `mkswap` and `swapon`. If using LVM, you can extend the swap logical volume online: after `swapoff`, use `lvextend` to resize it, then `mkswap` and `swapon`.
After extending the swap, its usage needs to be continuously monitored to evaluate the effect. Besides the `free` and `top` commands, `sar -S 1` can be used to view changes in swap usage, and `cat /proc/meminfo` provides detailed memory statistics. If swap usage is frequently and heavily used (e.g., consistently above 20%), it indicates a severe shortage of physical memory. Expanding swap is only a temporary measure; the long-term solution should be to increase physical memory or optimize application memory usage.
In extreme cases where there is no disk space left to create swap, consider using the zram kernel module to create compressed memory block devices as swap. This essentially trades CPU time for more available memory space, which can be effective in scenarios with insufficient memory but available CPU.
Regarding security, swap files may contain sensitive memory data. In cloud environments, if resources need to be released, swap file data should be cleaned up before deleting the instance: after using `swapoff`, overwrite the file with `dd` (e.g., `dd if=/dev/zero of=/swapfile bs=1M`) and then delete it. For environments with high security requirements, the `discard` parameter can be added to `/etc/fstab` or the `fstrim` command can be used (only applicable to disks that support TRIM). In summary, adding a Swap partition on CentOS is an effective emergency solution to address insufficient memory. The core steps include creating files, setting permissions, formatting, enabling and configuring automatic mounting. Optimizing the swappiness parameter can adjust the system's tendency to use Swap. However, Swap is essentially a trade-off between performance and availability; consistently high Swap usage is a clear signal that the system needs to expand physical memory or optimize applications. Administrators should combine monitoring data to configure and use Swap appropriately as a buffer component within the memory management system.
EN
CN