Guides

How to add swap space on Ubuntu and Debian: swap file, size and swappiness

Create a swap file with fallocate, enable it, keep it after reboots and tune swappiness. How much swap a small VPS needs, and when swap will not save you.

Published ~9 min read

To add swap on Ubuntu or Debian, create a swap file, format it as swap, switch it on and add it to /etc/fstab so it survives reboots. Six commands, as root or with sudo, give you 2 GB of swap:

2 GB swap file — Ubuntu, Debian, Rocky
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
swapon --show && free -h

swapon --show should now list /swapfile, and the Swap line of free -h should read 2.0Gi. Swap is a safety net for memory spikes, not extra RAM: it keeps the kernel from killing a process when memory runs out for a moment, but a server that needs it all the time is too small for its job. The sections below cover sizing, the swappiness setting, what to do when fallocate is refused, and how to resize or remove swap again.

If you came here from a process that died with “Killed”, our guide to the out-of-memory killer explains how to confirm that memory was the cause. Swap is also one step of our first ten minutes on a new server; this page is the long version.

Do I already have swap?

check first
swapon --show      # no output means no swap at all
free -h            # the Swap line shows total and used
cat /proc/swaps    # the same, straight from the kernel

Many VPS images ship without swap. Ubuntu installed with its regular server installer often has a swap file called /swap.img already. If swapon --show lists something, you do not need a second swap file; resize the existing one instead (see below).

How do I create a swap file step by step?

  1. 1Make sure there is room on the disk
    free space on /
    df -h /

    The swap file takes its full size on disk immediately. Leave enough free space for logs and updates afterwards.

  2. 2Create the file
    reserve 2 GB
    sudo fallocate -l 2G /swapfile

    fallocate reserves the space instantly. If a later step complains about the file, create it with dd instead, as described in the next section.

  3. 3Make it readable by root only
    permissions
    sudo chmod 600 /swapfile

    Swap can contain anything that was in memory, passwords and keys included. swapon warns about “insecure permissions” if you skip this.

  4. 4Format and enable it
    mkswap and swapon
    sudo mkswap /swapfile
    sudo swapon /swapfile
  5. 5Keep it after a reboot
    /etc/fstab
    # add the line only if it is not there yet
    grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
    
    # test the fstab line without rebooting
    sudo swapoff /swapfile && sudo swapon -a && swapon --show

    sudo echo … >> /etc/fstab does not work, because the redirect runs in your own shell without root rights; that is why the line goes through sudo tee -a.

Should I use fallocate or dd?

Use fallocate first; on ext4, the default on Ubuntu and Debian, it works and takes a second. Some filesystems refuse a swap file that was created that way, and then swapon says something like swapon: /swapfile: skipping - it appears to have holes or swapon failed: Invalid argument. In that case, write the file out in full with dd. It takes longer, because it really writes 2 GB of zeros:

dd instead of fallocate
sudo swapoff /swapfile 2>/dev/null; sudo rm -f /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

count is the size in megabytes: 1024 for 1 GB, 4096 for 4 GB. The same commands work on Rocky Linux and Alma, where the root filesystem is usually XFS; if fallocate is refused there, the dd variant is what Red Hat’s own documentation uses. On Alpine, which has no systemd, the fstab line is only activated by OpenRC’s swap service: run rc-update add swap boot once, and use dd if fallocate is not installed.

How much swap does a VPS need?

Less than the old rules of thumb suggest. “Twice the RAM” comes from a time when RAM was tiny, and the “at least as much as RAM” rule is about hibernation, which a server never does. For a VPS:

  • 1–2 GB of RAM: 1–2 GB of swap. Small boxes hit memory spikes from package updates, builds and database imports most often.
  • 2–8 GB of RAM: 1–2 GB as a cushion is plenty.
  • More than 8 GB: 1–2 GB still helps the kernel move memory that is never touched out of the way. More rarely pays off.

If you find yourself wanting 8 GB of swap on a 4 GB server, the server needs more RAM, not more swap. And swap costs disk: 2 GB is a tenth of a 20 GB plan, so on small disks stay at the lower end.

What is swappiness and what should I set?

vm.swappiness tells the kernel how readily to move memory to swap rather than drop file cache. The default is 60. On a server, a lower value such as 10 keeps your applications in RAM longer and uses swap mainly when memory actually runs short:

check, change, keep
cat /proc/sys/vm/swappiness          # current value, usually 60

sudo sysctl vm.swappiness=10          # takes effect now, gone after a reboot

# make it permanent
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system

Use a file in /etc/sysctl.d/ rather than /etc/sysctl.conf: it works on every current distribution, while some recent releases no longer read /etc/sysctl.conf at boot. Setting 0 does not switch swap off; it tells the kernel to avoid it until memory is nearly gone. To really switch swap off, use swapoff.

How do I resize or remove swap?

A swap file in use cannot be resized. Switch it off, change it, switch it on again. Before swapoff, check free -h: everything currently in swap has to fit into free RAM, or swapoff fails, or the OOM killer steps in.

resize /swapfile to 4 GB
free -h                              # swap "used" must fit into "available"
sudo swapoff /swapfile
sudo fallocate -l 4G /swapfile       # or dd ... count=4096, see above
sudo mkswap /swapfile
sudo swapon /swapfile
swapon --show

The fstab line stays the same, because it names the file, not its size. To shrink the file, delete it and create it again at the new size. To remove swap completely:

remove the swap file
sudo swapoff /swapfile
sudo sed -i '\|^/swapfile |d' /etc/fstab
sudo rm /swapfile
swapon --show                        # no output: no swap left

Do not skip the fstab edit. A line pointing at a file that no longer exists does not normally stop the boot, but it leaves a failed swap unit and an error in the log behind, every time the server starts.

Is zram an alternative to a swap file?

zram creates a compressed swap device in RAM. Memory that would be written to disk is compressed and kept in memory instead; how much room that wins depends on the data, and text and typical application memory compress well. It costs some CPU and saves disk I/O, which suits small servers with a fast CPU and a small disk. On Debian and Ubuntu, the zram-tools package sets it up; you can keep a swap file next to it as an overflow, and the kernel uses the zram device first because of its higher priority.

zram on Debian and Ubuntu
sudo apt install -y zram-tools
# size and compression in /etc/default/zramswap, for example:
#   ALGO=zstd
#   PERCENT=25
sudo systemctl restart zramswap
swapon --show                        # /dev/zram0 appears with a higher priority

When does swap not help?

When the server needs more memory than it has all the time, not only during a spike. Then the kernel keeps moving pages out to disk and back in, everything slows down, and swap is only delaying the problem. Watch it for a minute:

is the server constantly swapping?
vmstat 1 10                          # watch the si and so columns
cat /proc/pressure/memory            # memory pressure, where the kernel has it enabled
  • si and so mostly 0, with an occasional burst — swap is doing its job. Nothing to fix.
  • si and so non-zero in almost every line — the server is thrashing. The memory is simply too small for what runs on it.
  • kswapd0 near the top of top — the kernel thread that reclaims memory is busy, the same symptom from another angle. Our guide to high CPU usage on a VPS explains why memory pressure shows up as CPU load.

The fix then is less memory use, such as smaller database buffers, fewer workers or builds done elsewhere, or more RAM. How to cap one service so it cannot take the whole box down is in the OOM guide’s section on limits.

Which process is using swap?

Each process reports its own share in /proc/<pid>/status as VmSwap. The quick look is grep VmSwap /proc/*/status; this version sorts it and adds the process names:

top swap users
for f in /proc/[0-9]*/status; do
  awk '/^Name:/ {n=$2} /^VmSwap:/ && $2>0 {print $2, "kB", n}' "$f" 2>/dev/null
done | sort -rn | head

A big process with a lot in swap that runs fine is not a problem in itself: the kernel moved out what that process does not use. It becomes one when that process gets slow, because it keeps pulling its memory back from disk.

Can I add swap on any VPS?

On a KVM VPS, yes. The virtual machine runs its own kernel, so swap works exactly as on a physical server. Many container-based VPS types (OpenVZ, LXC) share the host’s kernel, and swapon fails there with “Operation not permitted”; the memory and swap limits are whatever the host gives the container. KVM vs OpenVZ explains the difference.

And when the honest answer is “more RAM”, it is usually cheaper than a slow server. On VMHeaven’s Standard KVM line, memory doubles from 4 GB on KVM 1 to 8 GB on KVM 2, and the largest plan has 64 GB. If your server reboots or freezes when memory runs out, rather than just losing a process, see VPS keeps rebooting.

Frequently asked

Does swap slow my server down?

Only when it is actively used. Pages that sit in swap untouched cost nothing, and some swap in use while RAM is free is normal. The server slows down when it keeps moving memory to disk and back, which shows as constantly non-zero si and so columns in 'vmstat 1'. At that point it needs less memory use or more RAM, not more swap.

Is swap bad for SSDs or enterprise storage?

Not in normal use. Occasional swapping writes little compared with what databases and logs write every day, and SSDs and enterprise storage are built for far more. Constant heavy swapping is a problem mainly for performance: on a VPS the swap file sits on the same virtual disk as everything else, so heavy swapping competes with your own disk I/O.

Swap file or swap partition: which is better?

On a VPS, a swap file. On current kernels it performs like a partition on common filesystems such as ext4 and XFS, and it can be created, resized or removed in a minute without repartitioning the disk. A partition is only worth it where a swap file is awkward, such as some Btrfs setups, or for hibernation, which servers do not use.

How do I check swap usage on Linux?

'free -h' shows total, used and free swap, and 'swapon --show' lists each swap file or partition with its size, usage and priority. To see which processes are in swap, read the VmSwap line in /proc/<pid>/status, for example with 'grep VmSwap /proc/*/status'. 'vmstat 1' shows in its si and so columns whether the system is swapping right now.

Related articles

All guides