How to Set Up Swap Partition in Linux

Publish: 2019-05-17 | Modify: 2019-05-17

The Swap partition, also known as virtual memory, is used in Linux systems to free up physical memory when it is running low. This allows the system to allocate the freed-up memory to currently running programs. The freed-up memory is temporarily stored in the Swap space, and can be restored to the physical memory when the programs need to run again. The system only performs Swap swapping when the physical memory is insufficient. Adjusting the Swap is crucial for the performance of Linux servers, especially web servers. By adjusting the Swap, it is sometimes possible to overcome performance bottlenecks and save on system upgrade costs.

Swap Partition

Setting up Swap Partition

This guide uses CentOS as an example, but the steps are 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
# Set it to start on boot
echo "/swap none            swap    default              0       0" >> /etc/fstab

With these simple commands, we have set up a 1024M Swap partition (virtual memory).

Other Commands

# View current memory usage
free -mt
# View current swap partition path
swapon -s
# Disable virtual memory, replace "/swap" with your swap partition path
swapoff /swap
# Enable virtual memory, replace "/swap" with your swap partition path
swapon /swap

Conclusion

In general, the size of the Swap space should be equal to or larger than the physical memory, with a recommended size of 2-2.5 times the physical memory. It is advisable to set up a Swap partition (swap) to improve system and business stability in a production environment. However, Swap is not a solution for long-term memory shortages, and it is recommended to add more physical memory in such cases.


Comments