How to Set Up a Swap Partition on Linux
The Linux Swap partition, also known as virtual memory, serves a critical function: when physical memory is insufficient, a portion of it is released and temporarily saved to the Swap space. This allows currently running programs to continue operating. When those programs need the data again, it is restored from Swap back to memory. This swapping process occurs only when physical memory is low. Adjusting Swap is crucial for Linux servers, especially web servers, as it can help overcome performance bottlenecks and reduce the need for hardware upgrades.

Setting Up a Swap Partition
This guide uses CentOS as an example, though the method is similar for other Linux systems.
# Create a 1024M partition using the dd command
dd if=/dev/zero of=/swap bs=1M count=1024
# Format the partition
mkswap /swap
# Enable virtual memory
swapon /swap
# Configure for automatic startup on boot
echo "/swap none swap default 0 0" >> /etc/fstab
With these simple commands, a 1024M swap partition (virtual memory) has been successfully configured.
Other Useful Commands
# View current memory usage
free -mt
# View the current swap partition path
swapon -s
# Disable virtual memory (replace /swap with your partition path)
swapoff /swap
# Enable virtual memory (replace /swap with your partition path)
swapon /swap
Summary
Generally, Swap space should be greater than or equal to the size of physical memory. Typically, the Swap space size should be 2 to 2.5 times the size of physical memory. In production environments, it is recommended to set up a swap partition to improve system and business stability. However, swap is not a cure-all; if memory shortage persists, adding physical memory is the better solution.