Description
A step-by-step guide to creating a swap file on Ubuntu, making it persistent across reboots, and tuning swappiness for better performance.
Disclamer
This article was made with Ai, but I have tested all these commands since I needed swap too
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 it, your 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.
Step 1: Create the Swap File
sudo fallocate -l 5G /swapfile
fallocate instantly allocates the space on disk without writing zeroes - fast and efficient. If for some reason fallocate isn't available, use dd as a fallback:
sudo dd if=/dev/zero of=/swapfile bs=1M count=5120
Step 2: Lock Down Permissions
sudo chmod 600 /swapfile
This ensures only root can read/write the swap file - important for security. A world-readable swap file is a potential data leak.
Step 3: Format as Swap
sudo mkswap /swapfile
You should see output like:
Setting up swapspace version 1, size = 5 GiB (5368705024 bytes)
no label, UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Step 4: Enable the Swap
sudo swapon /swapfile
Step 5: Make It Permanent
Without this step, your swap disappears after a reboot.
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
This appends the swap entry to /etc/fstab, which is read at boot time.
Step 6: Verify
free -h
You 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.0Gi
Swap is now active. ✅
Bonus: Tune Swappiness
By default, Ubuntu sets vm.swappiness=60, which tells the kernel to start using swap when RAM usage hits ~40%. For a desktop or workstation with plenty of RAM, that's too aggressive — you want to stay in RAM as long as possible.
Check your current value:
cat /proc/sys/vm/swappiness
Set it to 10 (apply immediately):
sudo sysctl vm.swappiness=10
Make it permanent across reboots:
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
Swappiness reference
| Value | Behavior |
|---|---|
0 |
Avoid swap entirely (only use in emergencies) |
10 |
Prefer RAM strongly — great for desktops/workstations |
60 |
Ubuntu default — balanced |
100 |
Swap aggressively |
For most desktop users with 4GB+ 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
Top comments (0)