Swap space is virtual memory that extends RAM by using disk storage. When physical memory fills up, Linux moves inactive pages to swap, preventing out-of-memory crashes and maintaining system stability.
Key Concepts
- Virtual Memory: Combination of RAM + swap space
- Swap File: Regular file used as swap space
- Swap Partition: Dedicated disk partition for swap
- Swappiness: Kernel parameter controlling swap usage
- Page: Fixed-size memory block moved to/from swap
Command Syntax
swapon [options] device/file
swapoff [options] device/file
- Enable/disable swap space
- Device can be partition or file path
Common Options
-a - Enable/disable all swap in /etc/fstab
-s - Display swap usage summary
-p priority - Set swap priority (0-32767)
-v - Verbose output
--show - Display swap areas
Practical Examples
Example 1: Check current swap status
|
|
Shows memory usage and active swap areas
Example 2: Create swap file
|
|
Creates and enables 2GB swap file
Example 3: Make swap permanent
|
|
Adds swap to fstab for automatic mounting
Example 4: Adjust swappiness
|
|
Views and sets swap aggressiveness (0-100)
Example 5: Remove swap space
|
|
Disables and removes swap file
Use Cases
- Low RAM systems: Extend available memory
- Hibernation: Store RAM contents to disk
- Memory spikes: Handle temporary high usage
- Stability: Prevent OOM killer activation
- Large applications: Support memory-intensive tasks
Related Commands
free - Display memory and swap usage
vmstat - Virtual memory statistics
mkswap - Set up swap area
top/htop - Monitor swap usage by process
cat /proc/swaps - Show swap areas
Tips & Troubleshooting
Performance Considerations
- SSD vs HDD: SSDs provide faster swap access
- Size: Typically 1-2x RAM, depends on use case
- Priority: Higher priority swap used first
- Multiple swap: Distribute across drives
Common Issues
- High swap usage: Check for memory leaks
- Swap thrashing: Reduce swappiness or add RAM
- Permission errors: Ensure correct ownership/perms
- Boot failures: Verify fstab entries
Best Practices
- Monitor swap usage with
sar -S - Keep swappiness low (10-20) for desktops
- Use swap files for flexibility
- Regular cleanup of unused swap areas
- Consider zram for better performance
Security Notes
- Swap may contain sensitive data
- Encrypt swap on security-critical systems
- Clear swap before system disposal