Check Current Swap Status
free -h
sudo swapon --show
Create and Configure Swap File
1. Create the swap file
# Create a 4GB swap file (adjust size as needed)
sudo fallocate -l 4G /swapfile
# Alternative method if fallocate isn't available
# sudo dd if=/dev/zero of=/swapfile bs=1024 count=4194304
2. Set proper permissions and format
sudo chmod 600 /swapfile
sudo mkswap /swapfile
3. Enable swap
sudo swapon /swapfile
4. Make it permanent
Add to /etc/fstab so it mounts on boot:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
5. Verify it’s working
free -h
sudo swapon --show
Optimize Swap Settings
Set swappiness (optional)
The vm.swappiness parameter controls how aggressively the Linux kernel uses swap space:
- 0-10: Minimal swapping - keeps data in RAM as long as possible (ideal for servers)
- 60: Default on most systems - balanced approach
- 100: Very aggressive swapping - moves data to swap readily
# For servers (conservative - avoid swap unless necessary)
echo 'vm.swappiness=5' | sudo tee -a /etc/sysctl.conf
# For desktops with limited RAM
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
Lower values prioritize keeping data in faster RAM, while higher values free up RAM more aggressively by moving data to slower disk-based swap.
How Much Swap Do You Need?
| RAM Size | Recommended Swap |
|---|---|
| < 4GB | 2x RAM size |
| 4-16GB | 1-1.5x RAM size |
| > 16GB | 2-4GB minimum |
Server considerations:
- Database servers: Minimal swap (2-4GB)
- Web servers: 1-2GB usually sufficient
- High-memory servers: 0.5-1x RAM or fixed amount
Remove Swap (if needed)
sudo swapoff /swapfile
sudo rm /swapfile
# Remove the line from /etc/fstab
That’s it! Your system now has additional virtual memory to handle memory spikes and prevent out-of-memory crashes.