Creating Swap Space
The first step in configuring swap is to create a swap file or partition. For most users, a swap file is more flexible and easier to manage than a dedicated partition. To create a 4GB swap file, use the following commands:
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 # Create a 4GB file filled with zeros
sudo chmod 600 /swapfile # Restrict permissions to root only
sudo mkswap /swapfile # Format the file as swap space
sudo swapon /swapfile # Enable the swap file immediately
To ensure the swap file is mounted automatically after a reboot, add the following line to /etc/fstab:
echo '/swapfile swap swap defaults 0 0' | sudo tee -a /etc/fstab
For systems requiring more swap or those preferring a traditional approach, you can create a swap partition using tools like fdisk or parted, format it with mkswap, and enable it with swapon. However, swap files are generally preferred for their simplicity.
Adjusting Swappiness
Swappiness is a kernel parameter that controls how aggressively the system moves data from RAM to swap. It ranges from 0 to 100, where 0 tells the kernel to avoid swap unless absolutely necessary, and 100 encourages aggressive swapping. For most servers, a value between 10 and 30 is ideal—it reduces unnecessary disk I/O while still providing a safety net for memory overflow. To adjust swappiness:
sudo sysctl vm.swappiness=10
/etc/sysctl.conf and add:vm.swappiness=10
Then apply the changes with:sudo sysctl -p
This setting is particularly useful for memory-intensive workloads, where excessive swapping can degrade performance.
Optimizing Swap Size
The appropriate swap size depends on your system’s physical memory and workload. While older guidelines suggested 2x physical memory, modern systems with ample RAM often need less. Here’s a more nuanced approach:
Monitoring Swap Usage
Regular monitoring helps you understand swap behavior and identify potential issues. Use these commands to track swap usage:
free -h
swapon --show
vmstat 1 # Shows swap in/out rates (si/so columns)
top # Check "Swap" column for individual processes
Monitoring helps you determine if your swap size is adequate or if you need to adjust swappiness.
Using Zram for Compressed Swap
Zram is a kernel feature that creates a compressed block device in RAM, acting as swap space. Unlike traditional swap on disk, zram avoids slow disk I/O by compressing data in memory. This is ideal for systems with limited RAM but can also improve performance by reducing reliance on disk-based swap. To set up zram:
sudo yum install zram-config
sudo systemctl start zram-config
/etc/zram-config.conf and set:ZRAM_DEVICE_SIZE=4G
Zram is particularly effective for servers with high memory pressure, as it provides faster swap access while conserving disk space.
Important Considerations