How to create Swap memory in Linux
Swap memory in Linux is a crucial part of system performance optimisation. It acts as an extension of your system’s physical RAM, allowing your computer to handle processes when the RAM is full. If you often run memory-intensive applications or work with servers that have limited RAM, enabling swap can prevent crashes and improve overall stability.

In this guide, we’ll walk you through how to create swap memory in Linux step by step.
Steps to create Swap memory in Linux
1. Check Existing Swap
Before creating a new swap, check if swap already exists:
swapon --show
free -h
If no output appears for swapon
, it means there is no active swap.
2. Create a Swap File
Let’s create a 2GB swap file (you can adjust size as needed):
sudo fallocate -l 2G /swapfile
If fallocate
is not available, you can use dd
:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048
3. Set Correct Permissions
For security, only root should access the swap file:
sudo chmod 600 /swapfile
4. Mark File as Swap
Convert the file into swap space:
sudo mkswap /swapfile
5. Enable Swap File
Activate swap immediately:
sudo swapon /swapfile
Verify with:
swapon --show
free -h
6. Make Swap Permanent
To ensure swap persists after reboot, add it to /etc/fstab
:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
7. Adjust Swappiness (Optional)
Swappiness controls how aggressively Linux uses swap (range: 0–100).
Check current value:
cat /proc/sys/vm/swappiness
For desktop systems, a lower value like 10
is recommended. To change:
sudo sysctl vm.swappiness=10
Make it permanent by adding to /etc/sysctl.conf
:
vm.swappiness=10
Best Practices for Swap Memory
Use swap as a backup, not a replacement for RAM.
For SSDs, keep swap smaller to reduce disk wear.
For servers, allocate 1–2x RAM as swap depending on workload.
Monitor swap usage regularly with
htop
orvmstat
.