Creating Swap Space
Swap can be configured as a dedicated partition or a swap file, depending on system requirements and disk layout. For partition-based setup, use fdisk or parted to create a new partition (e.g., /dev/sdb2), then format it with mkswap /dev/sdb2 and enable it via swapon /dev/sdb2. To make it persistent, add an entry to /etc/fstab (e.g., /dev/sdb2 swap swap defaults 0 0). For file-based setup, use fallocate -l 4G /swapfile (or dd if=/dev/zero of=/swapfile bs=1M count=4096 for older systems) to create a 4GB file, set strict permissions with chmod 600 /swapfile, format it with mkswap /swapfile, and enable it with swapon /swapfile. Add /swapfile none swap sw 0 0 to /etc/fstab for automatic mounting at boot.
Determining Optimal Swap Size
The ideal swap size depends on physical memory (RAM) and workload characteristics. Common recommendations include:
Tuning Swappiness Parameter
The vm.swappiness parameter controls the kernel’s tendency to use swap (range: 0–100). A lower value reduces swap usage (preferring to keep data in RAM), while a higher value increases it (useful for freeing RAM quickly). For most CentOS servers (especially production), set swappiness between 10–30 to minimize swap-induced latency. To adjust:
sudo sysctl vm.swappiness=10 (takes effect immediately).vm.swappiness=10 to /etc/sysctl.conf, then run sudo sysctl -p to apply changes. This setting is critical for maintaining performance on systems with sufficient RAM.Performance Optimization Techniques
sudo yum install zram-config, start the service with sudo systemctl start zram-config, and configure the size (e.g., ZRAM_DEVICE_SIZE=4G in /etc/zram-config.conf). Zram is ideal for systems with limited disk space or high I/O demands./etc/sysctl.conf:
vm.dirty_ratio=10 (max percentage of system memory for dirty pages before syncing to disk).vm.dirty_background_ratio=5 (percentage of memory for background writeback).sudo sysctl -p to apply. These settings improve performance for write-heavy workloads by delaying non-critical disk writes.Monitoring and Maintenance
Regularly monitor swap usage to identify potential issues (e.g., excessive swapping leading to performance bottlenecks). Key commands include:
free -h: Shows total, used, and free swap space in a human-readable format.swapon --show: Lists active swap devices/files and their sizes.vmstat 1: Displays real-time system statistics (including swap activity under “si” (swap in) and “so” (swap out)).top/htop: Monitors processes consuming excessive memory (potential triggers for swap usage).Important Considerations
/dev/sdb1 for swap instead of /dev/sda1 (root disk).