What Is Swap?
Swap is disk space used as overflow when physical RAM is exhausted. While much slower than RAM, it prevents out-of-memory crashes and process kills.
Check Current Swap
free -h
swapon --showCreate a Swap File
# Create a 2 GB swap file
sudo fallocate -l 2G /swapfile
# Set correct permissions
sudo chmod 600 /swapfile
# Format as swap
sudo mkswap /swapfile
# Enable swap
sudo swapon /swapfile
# Verify
free -hMake It Permanent
Add to /etc/fstab:
/swapfile none swap sw 0 0Tune Swappiness
Swappiness controls how aggressively Linux moves data from RAM to swap (0-100):
# Check current value
cat /proc/sys/vm/swappiness
# Set temporarily
sudo sysctl vm.swappiness=10
# Set permanently
echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.confRecommended Values
| Value | Behavior | Best For |
|---|---|---|
| 1-10 | Minimal swapping | Database servers, SSD storage |
| 30-40 | Moderate swapping | General purpose servers |
| 60 (default) | Balanced | Desktop systems |
Swap Size Guidelines
| RAM | Recommended Swap |
|---|---|
| 1 GB | 2 GB |
| 2 GB | 2-4 GB |
| 4-8 GB | 2-4 GB |
| 16+ GB | 2 GB (safety net) |
Remove Swap
sudo swapoff /swapfile
sudo rm /swapfile
# Remove the /etc/fstab entry