When your VPS runs out of RAM, applications crash. MySQL terminates, PHP processes die, and your website goes down. Swap space is a fallback – it uses disk space as emergency memory when RAM is full.
This guide shows you how to add swap space on Ubuntu 24.04.
What Is Swap Space?
Swap is a file or partition on your disk that the operating system uses as "overflow" memory. When your RAM fills up, the kernel moves less‑used pages to swap. It keeps your system running, though slower than real RAM.
Adding swap is especially useful for low‑spec VPS (1‑2 GB RAM) running WordPress or other dynamic applications. It prevents out‑of‑memory (OOM) crashes during traffic spikes.
Note: Swap is not a replacement for RAM. It's much slower (disk vs. memory). Use it as a safety net, not as a performance solution.
Step 1: Check Current Swap Usage
First, check if you already have swap configured:
sudo swapon --show
If you see nothing, you have no swap. Also check disk space:
df -h /
You need at least 2 GB free space to create a swap file.
Step 2: Create a Swap File
A swap file is the simplest method – you don't need to repartition your disk. Create a 2 GB swap file:
sudo fallocate -l 2G /swapfile
If fallocate fails (some filesystems don't support it), use dd instead:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048
Set the correct permissions:
sudo chmod 600 /swapfile
Step 3: Format the Swap File
sudo mkswap /swapfile
This prepares the file as a swap area. You'll see output confirming the size and UUID.
Step 4: Enable the Swap File
sudo swapon /swapfile
Verify it's active:
sudo swapon --show
You should see the swap file listed with its size.
Step 5: Make Swap Permanent
Without this step, the swap file disappears after reboot. Add it to /etc/fstab:
sudo nano /etc/fstab
Add this line at the end:
/swapfile none swap sw 0 0
Save and exit.
Step 6: Tune Swap Settings (Optional)
The swappiness value controls how aggressively the system uses swap. The default is 60 (0‑100 scale). Lower values prefer RAM; higher values prefer swap.
For VPS, 10‑30 is often better for performance:
sudo sysctl vm.swappiness=10
Make it permanent:
sudo nano /etc/sysctl.conf
Add:
vm.swappiness=10
When to Use Swap
Swap helps in these scenarios:
- Traffic spikes that temporarily exceed your RAM
- Background processes (like backups) that use extra memory
- Applications with memory leaks (swap buys you time to fix them)
It won't fix chronic memory shortage. If your VPS consistently uses swap, you need more RAM.
How Much Swap Should You Add?
| Server RAM | Recommended Swap |
|---|---|
| 512 MB – 1 GB | 1‑2 GB |
| 2 GB | 2 GB |
| 4 GB | 2‑4 GB |
| 8 GB+ | 4‑8 GB (optional) |
Removing Swap (If Needed)
To remove swap:
sudo swapoff /swapfile
sudo rm /swapfile
Remove the line from /etc/fstab.
Need a VPS to practice on? Check our recommended VPS providers.