Swap space is an area on your disk that acts as virtual memory when your physical RAM is fully used.
While swap is slower than RAM, it prevents applications from crashing due to memory shortages.
In this tutorial, you’ll learn how to add swap space in Ubuntu 20.04 using a swap file, configure it to load at boot, and optimize its performance.
1. Check if Swap Space Already Exists #
Run:
sudo swapon --show
If there’s no output, swap is not enabled. You can also check with:
free -h
If the Swap column shows 0B, no swap is active.
2. Check Available Disk Space #
Ensure you have enough free disk space:
df -h
Look for the row where Mounted on is /.
If you have a few GB free, you can proceed.
Tip: A common rule is to set swap space equal to or twice your RAM size. For systems with more than 4GB RAM, 2–4GB of swap is usually enough.
3. Create a Swap File #
For example, to create a 1 GB swap file:
sudo fallocate -l 1G /swapfile
Verify:
ls -lh /swapfile
4. Enable the Swap File #
-
Set correct permissions:
sudo chmod 600 /swapfile -
Format as swap space:
sudo mkswap /swapfile -
Enable it:
sudo swapon /swapfile -
Verify:
sudo swapon --show free -h
5. Make Swap Permanent (Enable at Boot) #
Without configuration, the swap file will be disabled after a reboot. To enable it permanently:
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
6. Optimize Swap Performance #
Adjust Swappiness #
Swappiness controls how often Linux uses swap:
0→ Use swap only when absolutely necessary.100→ Aggressively use swap.
Check current value:
cat /proc/sys/vm/swappiness
Set it temporarily (example: 10):
sudo sysctl vm.swappiness=10
Make it permanent:
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
Adjust Cache Pressure #
Cache pressure controls how quickly the system clears cached filesystem data. Lower values keep cache longer.
Check:
cat /proc/sys/vm/vfs_cache_pressure
Set it temporarily (example: 50):
sudo sysctl vm.vfs_cache_pressure=50
Make it permanent:
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
✅ Conclusion #
You’ve successfully added swap space in Ubuntu 20.04.
Your system now has extra virtual memory to handle heavy workloads or low-RAM situations.
⚠️ Keep in mind: swap is slower than RAM. If your system frequently runs out of memory, the best solution is still to upgrade your RAM.