Many cloud and VPS images start with no swap at all. That is fine until a backup job, a package upgrade or a traffic spike needs a little more memory than the server has. Then the kernel's out-of-memory (OOM) killer stops a process, and it is often your database or web application. A modest swap file gives the server a safety buffer for short memory peaks.
This guide shows how to:
- check whether the server already has swap,
- create a swap file the way the official manual recommends,
- secure it, turn it on and keep it after a reboot,
- set
vm.swappinessin a clean drop-in file, - resize or remove the swap file later, and
- tell normal swap use from a real memory problem.
The commands work on current Ubuntu and Debian releases with an ext4 or XFS root file system. Run them as a user with sudo rights. If your root file system is Btrfs, read the note in step 2 first.
1. Check for existing swap and free disk space
swapon --show
free -h
If swapon --show prints nothing, the server has no active swap. In the output of free -h, the Swap: line then shows 0B. If swap already exists (a swap partition or a file such as /swap.img), decide whether you want to resize it instead of adding a second one. See step 6.
Next, make sure the disk has room for the file. The swap file takes its full size on disk at once:
df -h /
Do not fill the disk with swap. Leave plenty of free space for logs, updates and your data.
How big should the swap file be?
There is no single correct size. On a server, swap is a buffer for short peaks, not a replacement for RAM. Servers normally do not hibernate, so you do not need swap at least as large as RAM for that purpose. As a starting point that works for many small servers:
| Server RAM | Reasonable starting swap size | Comment |
|---|---|---|
| 1 GB to 2 GB | 1 GB to 2 GB | Small VPS; swap often prevents OOM kills during upgrades and backups |
| 4 GB to 8 GB | 2 GB | Enough for short peaks on most web and application servers |
| 16 GB or more | 2 GB to 4 GB | Mainly a safety net; size by what your workload actually needs |
These are practical starting values, not official rules. Follow your application vendor's guidance where it exists. Some software, for example certain database setups, has its own recommendations about swap.
2. Create the swap file
The swapon(8) manual explains that the kernel writes to a swap file directly, without help from the file system, so the file must not contain holes. It recommends creating the file with dd and /dev/zero, because preallocated files (for example from fallocate) can be a problem on some file systems. This example creates a 2 GiB file at /swapfile:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
bs=1M count=2048 means 2048 blocks of 1 MiB, which is 2 GiB. Change count for a different size, for example count=1024 for 1 GiB. On a slow disk this can take a minute.
Btrfs note: on Btrfs, a swap file must not use copy-on-write or compression, and the plain dd method above is not enough. Follow the swap file section of the official Btrfs documentation instead.
3. Secure the file, format it and turn it on
Swap can hold any memory page of any process, including passwords, keys and session data. Only root may read it:
sudo chmod 600 /swapfile
ls -lh /swapfile
The permissions should read -rw------- with owner root. If the permissions are too open, mkswap and swapon print an "insecure permissions" warning.
Now write the swap signature and activate the file:
sudo mkswap /swapfile
sudo swapon /swapfile
Check the result:
swapon --show
free -h
Example output of swapon --show:
NAME TYPE SIZE USED PRIO
/swapfile file 2G 0B -2
The swap file is active now, but only until the next reboot.
4. Make the swap file permanent in /etc/fstab
Back up /etc/fstab first, then add one line for the swap file:
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
A mistake in /etc/fstab can stop the server from booting normally, so test the entry before you reboot. Check the file syntax, then turn the swap file off and let the system turn it on again from /etc/fstab:
sudo findmnt --verify
sudo swapoff /swapfile
sudo swapon -a
swapon --show
If swapon --show lists /swapfile again, the entry works. On systemd-based systems, swap entries in /etc/fstab are turned into swap units at boot. You can see them with:
systemctl --type swap
5. Tune vm.swappiness
vm.swappiness tells the kernel how willing it is to swap out process memory compared with dropping file cache. According to the Linux kernel documentation, the value ranges from 0 to 200 and the default is 60. Lower values make the kernel prefer keeping application memory in RAM.
Check the current value:
cat /proc/sys/vm/swappiness
For many servers where swap is only a safety net, a lower value such as 10 is a common choice. Set it in a drop-in file in /etc/sysctl.d/ instead of editing /etc/sysctl.conf. Drop-ins are easy to review and remove:
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system
cat /proc/sys/vm/swappiness
sysctl --system loads all sysctl configuration files, so the new value applies now and after every reboot. Avoid vm.swappiness=0 unless you know you need it: it makes the kernel avoid swapping almost completely, and the OOM killer may act sooner under pressure. Measure before and after a change; the best value depends on your workload.
6. Resize or remove the swap file
To change the size, turn the swap file off, create it again with the new size and turn it back on. swapoff moves swapped pages back into RAM, so run it only when there is enough free memory (check free -h), ideally at a quiet time.
sudo swapoff /swapfile
sudo rm /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
swapon --show
The line in /etc/fstab stays the same, because the path did not change.
To remove the swap file completely:
sudo swapoff /swapfile
sudo sed -i.bak '\|^/swapfile |d' /etc/fstab
sudo rm /swapfile
sudo findmnt --verify
The sed command deletes the /swapfile line and keeps a backup as /etc/fstab.bak. Open /etc/fstab afterwards to confirm that only that line was removed.
7. Watch swap activity
Some swap use is normal. The kernel may move memory pages that are rarely used to swap and keep RAM for active work and file cache. What matters is constant swapping in and out.
vmstat 1 5
Look at the si (swap in) and so (swap out) columns. Values that stay at or near zero mean swap is just holding idle pages. Values that stay high every second mean the server does not have enough RAM for its workload, and it will feel slow.
To see which processes use swap:
for f in /proc/[0-9]*/status; do
awk '/^Name:/{n=$2} /^VmSwap:/{if ($2 > 0) print $2, "kB", n}' "$f" 2>/dev/null
done | sort -rn | head
To check whether the OOM killer has already stopped processes, search the kernel log:
sudo journalctl -k | grep -i -E 'out of memory|oom-kill'
Common problems
swapon: /swapfile: swapon failed: Invalid argument. The file may contain holes (often afterfallocate) or be on a file system that needs special steps, such as Btrfs. Recreate it withddas in step 2, or follow your file system's documentation.- "insecure permissions" warning. Run
sudo chmod 600 /swapfileand make sure root owns the file. - Swap is gone after a reboot. The
/etc/fstabline is missing or wrong. Check it withgrep swap /etc/fstaband test withsudo swapon -a. - The server is slow and swap is full. Swap only hides a lack of RAM for a short time. Find the process that uses the memory, fix memory leaks or limits in your application, or add RAM. A bigger swap file will not make a memory-starved server fast.
swapofftakes a long time or fails. There is not enough free RAM to take back the swapped pages. Stop non-essential services first or wait for a quieter time.
Quick checklist
- Check existing swap with
swapon --showand free disk space withdf -h /. - Create the file with
dd if=/dev/zero of=/swapfile bs=1M count=2048. - Run
chmod 600,mkswapandswapon. - Add
/swapfile none swap sw 0 0to/etc/fstaband test withswapoffandswapon -a. - Optionally set
vm.swappinessin/etc/sysctl.d/99-swappiness.confand apply it withsysctl --system. - Watch
siandsoinvmstat; constant swapping means the server needs more RAM or less load.
Sources
- util-linux manual: swapon(8) (swap files, holes, dd recommendation, swapoff)
- util-linux manual: mkswap(8)
- Linux kernel documentation: /proc/sys/vm (swappiness)
- Linux manual: fstab(5) and findmnt(8)
- systemd manual: systemd.swap(5) and sysctl.d(5)
- Btrfs documentation: Swapfile
