Linux systems rely on RAM for running applications smoothly. But what happens when your memory runs out? That’s where swap space comes in. A swap file acts as backup memory on your disk, preventing crashes when your system is under heavy load.
Unlike swap partitions, swap files are flexible — you can create, resize, or delete them easily without touching your disk partitions.
In this guide, we’ll cover:
✅ What swap is
✅ Why swap is important
✅ How to create a swap file in Linux
✅ Distro-specific notes (Ubuntu, Fedora, AlmaLinux, etc.)
✅ Tuning tips for better performance
Swap = disk space used as virtual memory when RAM is full.
Keeps your system running under heavy load.
Prevents “Out of Memory (OOM)” errors.
Should not replace physical RAM — it’s slower than real memory.
👉 Think of swap like an emergency spare tire 🚗 — not ideal for everyday driving, but it saves you when you’re stuck.
fallocate
(faster)sudo fallocate -l 1G /swapfile
dd
(more compatible)sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
👉 This creates a 1 GB swap file. Adjust 1G
or count=1024
depending on your needs.
Only root should read/write the swap file:
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Check if it’s active:
swapon --show
free -h
Add entry in /etc/fstab
:
/swapfile none swap sw 0 0
This ensures swap activates automatically after every reboot.
The swappiness value (0–100) tells Linux how aggressively it uses swap.
0
→ avoid swap unless absolutely needed.
60
(default) → balanced.
10
→ recommended for desktops/servers (prefer RAM).
Check current value:
cat /proc/sys/vm/swappiness
Set swappiness to 10:
sudo sysctl vm.swappiness=10
Make it permanent by adding to /etc/sysctl.conf
:
vm.swappiness = 10
Newer Ubuntu versions often create a swap file by default.
Check with:
swapon --show
Works out of the box with fallocate
.
If SELinux complains, apply context:
sudo chcon system_u:object_r:swapfile_t:s0 /swapfile
Swap file is often preferred over partitions for flexibility.
✔️ Low-RAM VPS (1–2 GB)
Create a 2 GB swap file to prevent out-of-memory errors when compiling code.
✔️ Desktop Optimization
Lower swappiness to 10
to keep apps in RAM and reduce lag.
Run:
free -h
Example output:
total used free shared buff/cache available
Mem: 2.0G 1.2G 200M 100M 600M 600M
Swap: 1.0G 0B 1.0G
🎉 Done! You now have a working swap file in Linux.
A Linux swap file is a simple yet powerful way to give your system breathing room under heavy workloads. Whether you’re on Ubuntu, Fedora, AlmaLinux, or Arch, the steps are straightforward.
👉 Use swap as a safety buffer, not a replacement for RAM.
👉 Tune swappiness for optimal performance.
👉 Monitor usage with htop
or vmstat
.
With a properly configured swap file, your Linux system will run smoother, safer, and more resilient 🚀.