How to Add Swap Space on Ubuntu (5GB Example)
Source: Dev.to
Why Swap Matters
Swap is disk space that your OS uses as overflow when physical RAM fills up. Without it, the kernel may start killing processes (the dreaded OOM killer) when memory is exhausted. With swap, the system degrades gracefully instead of crashing.
My setup: 7.57 GB RAM, 0 KB swap. Adding 5 GB swap gives the system room to breathe under heavy loads.
Steps to Add Swap
Step 1: Create the Swap File
sudo fallocate -l 5G /swapfileIf fallocate isn’t available, use dd as a fallback:
sudo dd if=/dev/zero of=/swapfile bs=1M count=5120Step 2: Lock Down Permissions
sudo chmod 600 /swapfileThis ensures only root can read/write the swap file, preventing potential data leaks.
Step 3: Format as Swap
sudo mkswap /swapfileTypical output:
Setting up swapspace version 1, size = 5 GiB (5368705024 bytes)
no label, UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxStep 4: Enable the Swap
sudo swapon /swapfileStep 5: Make It Permanent
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstabAppending this line to /etc/fstab ensures the swap is activated at boot.
Step 6: Verify
free -hYou should see something like:
total used free shared buff/cache available
Mem: 7.5Gi 3.2Gi 1.1Gi 512Mi 3.2Gi 3.6Gi
Swap: 5.0Gi 0B 5.0GiSwap is now active. ✅
Bonus: Tune Swappiness
Ubuntu defaults to vm.swappiness=60, which starts using swap when RAM usage hits ~40 %. For desktops or workstations with ample RAM, a lower value is preferable.
Check the current value
cat /proc/sys/vm/swappinessSet it to 10 (apply immediately)
sudo sysctl vm.swappiness=10Make it permanent
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.confSwappiness Reference
| Value | Behavior |
|---|---|
0 | Avoid swap entirely (use only in emergencies) |
10 | Prefer RAM strongly — great for desktops/workstations |
60 | Ubuntu default — balanced |
100 | Swap aggressively |
For most desktop users with 4 GB+ RAM, 10 is the sweet spot.
Quick Summary
# 1. Create
sudo fallocate -l 5G /swapfile
# 2. Secure
sudo chmod 600 /swapfile
# 3. Format
sudo mkswap /swapfile
# 4. Enable
sudo swapon /swapfile
# 5. Persist
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
# 6. Verify
free -h
# Bonus: tune swappiness
sudo sysctl vm.swappiness=10
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf