How to create swap space on Linux
Swap space is disk space that Linux uses as extra memory when the RAM is full. Without it, a VPS with little RAM can kill processes such as MySQL or PHP when memory runs out (the "Out of memory" killer). This guide shows how to create swap space on Linux with a swap file, make it permanent, and tune it, on AlmaLinux and most other distributions.
Step 1: Check memory and existing swap
free -h
swapon --show
df -h /
If swapon --show prints nothing, the server has no swap. Make sure you have enough free disk space for the file.
Step 2: Create the swap file
This example creates a 2 GB swap file. A common rule of thumb for small servers is swap equal to the RAM, up to a few GB.
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
The chmod 600 step is important: only root should be able to read the swap file, because it can contain data from memory.
Step 3: Make it permanent
Add the swap file to /etc/fstab so it turns on after a reboot. Back up the file first, because a broken fstab can stop the server from booting:
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap defaults 0 0' | sudo tee -a /etc/fstab
Check that the line was added only once with cat /etc/fstab, then verify with free -h.
Step 4: Tune swappiness (optional)
Swappiness (0-100) controls how eagerly the kernel moves memory to swap. On a server, a low value such as 10 keeps active data in RAM and uses swap only under pressure:
cat /proc/sys/vm/swappiness
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl -p /etc/sysctl.d/99-swappiness.conf
How to remove the swap file
sudo swapoff /swapfile
# remove the /swapfile line from /etc/fstab, then:
sudo rm -f /swapfile
Common problems
- "swapon failed: Invalid argument" or "Operation not permitted": some container-based virtual servers do not allow swap inside the VPS. Contact support to confirm what your plan supports.
- "swapon: insecure permissions": run
sudo chmod 600 /swapfile. - Swap is gone after reboot: the
/etc/fstabline is missing or has a typo. - The server is slow and swap is always full: find what uses memory with
top(press Shift+M) and reduce it, or add RAM.
Frequently asked questions
How big should the swap file be?
For a small VPS, 1-2 GB or the same as the RAM is usually enough. Very large swap does not help; it only hides a memory shortage.
Can I add swap on a cPanel server?
Yes, if you have root access to the VPS or dedicated server. On shared hosting, swap is managed by the server and you cannot change it.
Will swap slow down my server?
Only when it is actually used heavily. Having swap available does not slow anything down.