How to Add a Swap File on Linux
A swap file acts as an overflow for system memory (RAM). If your server runs out of RAM, the swap file can help prevent crashes or instability.
1. Check If Swap Already Exists
sudo swapon --show
If no output appears, you don’t have any active swap configured.
2. Create a Swap File
This example creates a 2 GB swap file. You can change the value if needed:
sudo fallocate -l 2G /swapfile
If fallocate
is not supported:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048
3. Set Proper Permissions
sudo chmod 600 /swapfile
4. Format the File as Swap
sudo mkswap /swapfile
5. Enable the Swap File
sudo swapon /swapfile
6. Make It Persistent After Reboot
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
7. Adjust Swapiness (Optional)
This controls how aggressively the system uses swap (default is 60):
sudo sysctl vm.swappiness=10
Make permanent:
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
8. Verify Everything
free -h
sudo swapon --show
Summary
Adding a swap file is a simple but effective way to improve your server’s stability, especially on low-memory VPS systems. Use it wisely and monitor memory usage to ensure optimal performance.