What is Swap?
Swap is disk space used as virtual memory when physical RAM is full. It prevents out-of-memory crashes but is much slower than RAM.
Check Current Swap
free -h
swapon --showCreate a Swap File
# Create 2 GB swap file
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# Verify
free -hMake It Permanent
Add to /etc/fstab:
/swapfile none swap sw 0 0Tune Swappiness
Swappiness (0-100) controls how aggressively Linux uses swap. Lower = prefer RAM.
# Check current value
cat /proc/sys/vm/swappiness
# Set to 10 (good for web servers)
sudo sysctl vm.swappiness=10
# Make permanent
echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.confRecommended Swap Sizes
- 1 GB RAM → 2 GB swap
- 2-4 GB RAM → same as RAM
- 8+ GB RAM → half of RAM or 4 GB (whichever is smaller)
Remove Swap
sudo swapoff /swapfile
sudo rm /swapfile
# Remove the line from /etc/fstab