Set up and optimize Linux swap space for better system performance. Learn to create swap files, configure swappiness parameters, and monitor memory usage across different Linux distributions.
Prerequisites
- Root or sudo access
- At least 2GB free disk space
- Basic Linux command line knowledge
What this solves
Linux swap space acts as virtual memory when your system runs low on physical RAM. Without proper swap configuration, your system may freeze or kill processes under memory pressure. This tutorial shows you how to create swap files, optimize memory management parameters, and monitor swap performance for better system stability.
Step-by-step configuration
Check current swap configuration
First, examine your existing swap setup to understand the current state of virtual memory.
sudo swapon --show
free -h
cat /proc/swaps
If no swap is configured, the output will be empty. The free -h command shows total memory and swap usage in human-readable format.
Create a swap file
Create a dedicated swap file instead of a swap partition for more flexibility. We'll create a 2GB swap file, but adjust the size based on your system's RAM.
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
Enable the swap file
Activate the swap file immediately and verify it's working correctly.
sudo swapon /swapfile
sudo swapon --show
free -h
You should now see the swap file listed and available swap memory in the output.
Make swap permanent
Add the swap file to /etc/fstab so it activates automatically on boot.
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
This entry tells the system to mount the swap file at boot time with appropriate swap options.
Configure swappiness parameter
Swappiness controls how aggressively the kernel swaps memory pages to disk. The default value of 60 is often too high for desktop systems and servers with sufficient RAM.
cat /proc/sys/vm/swappiness
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
A swappiness value of 10 makes the kernel prefer keeping data in RAM and only swap when necessary. For servers with lots of RAM, consider values between 1-10.
Configure cache pressure
The vfs_cache_pressure parameter controls how aggressively the kernel reclaims memory used for caching directory and inode objects.
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
Setting this to 50 makes the kernel less likely to reclaim cache memory, improving filesystem performance. The default value is 100.
Apply kernel parameter changes
Reload sysctl configuration to apply the new memory management parameters without rebooting.
sudo sysctl -p
sysctl vm.swappiness vm.vfs_cache_pressure
The output should show your new parameter values are active.
Set up swap monitoring
Create a simple script to monitor swap usage and get alerts when swap usage is high.
#!/bin/bash
SWAP_USED=$(free | grep Swap | awk '{print ($3/$2)*100}')
SWAP_THRESHOLD=50
if (( $(echo "$SWAP_USED > $SWAP_THRESHOLD" | bc -l) )); then
echo "Warning: Swap usage is ${SWAP_USED}%"
echo "Current memory status:"
free -h
echo "Top memory-consuming processes:"
ps aux --sort=-%mem | head -10
fi
sudo chmod +x /usr/local/bin/check-swap.sh
Install monitoring dependencies
Install the bc calculator for floating-point arithmetic in the monitoring script.
sudo apt update
sudo apt install -y bc
Schedule regular swap monitoring
Add a cron job to check swap usage every 15 minutes and log warnings.
echo '/15 * /usr/local/bin/check-swap.sh >> /var/log/swap-monitor.log 2>&1' | sudo crontab -
This creates a log file at /var/log/swap-monitor.log with swap usage warnings and system information.
Verify your setup
Check that swap is active and properly configured with the right parameters.
sudo swapon --show
free -h
sysctl vm.swappiness vm.vfs_cache_pressure
cat /proc/swaps
grep swap /etc/fstab
Test the monitoring script manually to ensure it works correctly:
sudo /usr/local/bin/check-swap.sh
sudo crontab -l
Advanced swap optimization
Configure multiple swap files
For systems with high memory demands, you can create multiple swap files across different storage devices for better I/O distribution.
sudo fallocate -l 1G /swapfile2
sudo chmod 600 /swapfile2
sudo mkswap /swapfile2
sudo swapon -p 5 /swapfile2
The -p 5 option sets priority. Higher priority swap devices are used first. Add to fstab with priority:
echo '/swapfile2 none swap sw,pri=5 0 0' | sudo tee -a /etc/fstab
Monitor swap I/O performance
Use iostat to monitor swap device performance and identify I/O bottlenecks.
sudo apt install -y sysstat
iostat -x 1 5
Watch for high %iowait values during swap activity, which indicate storage bottlenecks. You can learn more about advanced I/O monitoring in our iostat and disk performance tutorial.
Tune memory overcommit settings
Configure how the kernel handles memory allocation requests that exceed available RAM plus swap.
echo 'vm.overcommit_memory=1' | sudo tee -a /etc/sysctl.conf
echo 'vm.overcommit_ratio=50' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
Setting overcommit_memory=1 allows the kernel to overcommit memory, while overcommit_ratio=50 limits overcommit to 50% of RAM plus swap space.
Performance monitoring commands
Use these commands to monitor memory and swap performance in real-time:
# Real-time memory usage
watch -n 2 free -h
Memory usage by process
ps aux --sort=-%mem | head -20
Swap usage details
cat /proc/meminfo | grep -i swap
Virtual memory statistics
vmstat 2 10
Detailed swap information
cat /proc/swaps
Common issues
| Symptom | Cause | Fix |
|---|---|---|
| Swap file creation fails | Insufficient disk space | df -h to check space, create smaller swap file |
| High swap usage with available RAM | Swappiness too high | Lower vm.swappiness to 10 or less |
| System slow with swap active | Swap on slow storage | Move swap to SSD or add more RAM |
| Swap not persistent after reboot | Missing fstab entry | Add swap entry to /etc/fstab |
| Cannot create swap file | File permissions or SELinux | Use sudo and check setsebool -P use_execmem 1 |
| Out of memory despite swap | Swap exhausted | Increase swap size or add more RAM |
Next steps
- Configure memory cgroups for container workloads
- Monitor system performance with htop and process analysis
- Advanced kernel parameter tuning with sysctl
- Set up ZRAM compression for better memory utilization
- Monitor memory and swap with Prometheus and Grafana