When the amount of physical memory (RAM) is full, swap space in Linux is used. Non-active pages in memory are moved to the swap memory if the system requires more memory resources.
Before You Begin
Swap should not be seen as a replacement to physical memory. Since swap space is on the hard drive, it has slower access time than physical memory.
Calculating Swap Space
Generally, swap space should be:
- 2x physical RAM for up to 2 GB of RAM
- Additional 1x physical RAM above 2 GB
- Never less than 32 MB
- For systems with >32 GB RAM, around 1/2 physical RAM
Creating the Swap File
Steps to create swap space:
- Create swap file:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152
- Set permissions:
sudo chmod 600 /swapfile
- Set up swap area:
sudo mkswap /swapfile
- Activate swap:
sudo swapon /swapfile
- Add to
/etc/fstab
:
/swapfile swap swap defaults 0 0
Verifying Swap Space
Check if swap is active:
free -h
swapon --show
Adjusting Swappiness
The swappiness parameter controls the tendency of the kernel to move processes out of physical memory:
# Check current swappiness
cat /proc/sys/vm/swappiness
# Temporarily change swappiness
sudo sysctl vm.swappiness=60
To make it permanent, add to /etc/sysctl.conf
:
vm.swappiness=60
Removing Swap File
If you need to remove the swap file:
sudo swapoff /swapfile
sudo rm /swapfile
Also remove the entry from /etc/fstab
.
Conclusion
Adding swap space to CentOS Stream 8 can help improve system performance when physical memory is limited. Remember to monitor your systemβs memory usage and adjust swap size accordingly.