Server Monitoring8 min read

    How to Add or Resize Swap Space on Linux

    By Amir— Reliability & Network Engineering
    Share

    Swap space is disk the kernel can use as overflow for memory. On a server it is less about "running more than fits in RAM" and more about degrading gracefully: when memory runs out, a machine with swap slows down and gives you time to react; a machine without swap has its biggest process killed by the OOM killer — usually the database, usually at 3 a.m. Many cloud images ship with no swap at all, so adding some is one of the first things to check on a new box.

    This guide covers checking what you have, adding a swap file correctly on each common filesystem, making it survive reboots, resizing and removing it, the vm.swappiness knob, when zram beats a swap file, and how to read vmstat to tell healthy swap use from thrashing.

    Check current swap

    sudo swapon --show
    # NAME      TYPE SIZE USED PRIO
    # /swapfile file   2G   0B   -2
    
    free -h
    #                total        used        free      shared  buff/cache   available
    # Mem:           7.7Gi       3.1Gi       1.2Gi        85Mi       3.4Gi       4.3Gi
    # Swap:          2.0Gi          0B       2.0Gi
    

    No output from swapon --show and Swap: 0B in free means there is none. cat /proc/swaps shows the same information.

    How much swap?

    The old "twice the RAM" rule is from an era of 512 MB machines. Practical guidance for servers:

    RAM Suggested swap Why
    ≤ 2 GB 2 × RAM Small boxes run out of headroom fast
    2–8 GB = RAM Covers short spikes; enough for hibernation on desktops
    8–64 GB 4–8 GB A safety margin, not a working set
    > 64 GB 4–8 GB, or none with careful OOM tuning Swapping tens of GB is never fast enough to be useful

    If a process genuinely needs more memory than the machine has, swap buys minutes, not a solution. Treat swap use as a signal to monitor and fix, not as capacity.

    Add a swap file (ext4 and XFS)

    A swap file is simpler than a swap partition and performs the same on modern kernels. Replace 2G with the size you want.

    sudo fallocate -l 2G /swapfile
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
    

    Verify:

    sudo swapon --show
    free -h
    

    Three notes on those four commands:

    • fallocate is instant; dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress does the same job but actually writes the zeros. Use dd only when fallocate is unsupported (some older or network filesystems).
    • chmod 600 is not optional. swapon warns loudly if the file is world-readable because memory contents would be readable by any user.
    • mkswap writes a swap signature; the file is useless to the kernel without it.

    Btrfs needs two extra steps

    Btrfs copy-on-write and compression are incompatible with swap. On Btrfs the file must be created with copy-on-write disabled before anything is written to it:

    sudo truncate -s 0 /swapfile
    sudo chattr +C /swapfile
    sudo fallocate -l 2G /swapfile
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
    

    On Btrfs tools 6.1 and later the whole sequence is one command: sudo btrfs filesystem mkswapfile --size 2g /swapfile. The swap file must also live on a single-device filesystem (no RAID profiles) and the subvolume cannot be snapshotted while swap is active. If you see swapon: /swapfile: swapon failed: Invalid argument on Btrfs, one of these rules was broken — delete the file and redo it with chattr +C first.

    Make it permanent

    swapon lasts until reboot. Add a line to /etc/fstab:

    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
    

    Then prove the entry is valid without rebooting:

    sudo swapoff /swapfile
    sudo swapon -a          # activates everything in fstab
    sudo swapon --show
    

    If swapon -a errors, fix /etc/fstab now — a bad fstab line can drop the next boot into emergency mode.

    Resize swap

    Swap files cannot be grown in place. Deactivate, recreate, reactivate:

    sudo swapoff /swapfile
    sudo rm /swapfile
    sudo fallocate -l 4G /swapfile
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
    

    swapoff has to move everything currently in swap back into RAM. If swap is heavily used and RAM is tight, swapoff can take a long time or fail with swapoff failed: Cannot allocate memory. In that case add a second, larger swap file first, swapon it, then swapoff the old one.

    Multiple swap areas are fine; give them priorities with pri= in fstab if you want the fast NVMe one preferred:

    /swap-nvme none swap sw,pri=10 0 0
    /swap-sata none swap sw,pri=5  0 0
    

    Remove swap

    sudo swapoff /swapfile
    sudo sed -i '\|^/swapfile |d' /etc/fstab
    sudo rm /swapfile
    

    Tune how eagerly the kernel swaps: vm.swappiness

    vm.swappiness (0–200, default 60) sets how willing the kernel is to swap out anonymous memory versus dropping file cache. Lower values keep application memory in RAM longer at the cost of less page cache; higher values do the opposite.

    cat /proc/sys/vm/swappiness
    sudo sysctl vm.swappiness=10
    echo 'vm.swappiness = 10' | sudo tee /etc/sysctl.d/99-swappiness.conf
    

    10 is a common choice for database and application servers: swap exists as a safety net but is not used proactively. 1 is "only when otherwise out of memory". 0 on modern kernels still allows swapping under pressure, it just disables proactive swapping — it does not turn swap off.

    When zram is the better choice

    zram creates a compressed block device in RAM and swaps to that. Pages compress 2–4× typically, so a 2 GB zram device costs roughly 0.5–1 GB of real memory and is far faster than disk. It is the default on Fedora and increasingly common on small VMs and containers hosts without fast disks.

    # Fedora / RHEL 9 / AlmaLinux 9 / Rocky 9
    sudo dnf install -y zram-generator-defaults
    sudo systemctl daemon-reload
    sudo systemctl start systemd-zram-setup@zram0.service
    
    # Ubuntu / Debian
    sudo apt install -y zram-tools
    sudo systemctl enable --now zramswap
    

    Check with swapon --show — you will see /dev/zram0 with a high priority, so it is used before any disk swap file. zram and a disk swap file can coexist: zram absorbs spikes, the file is the last resort.

    Is swap being used, or thrashed?

    Some swap used is normal and even good — the kernel parks pages nobody has touched in hours. What hurts is constant swapping in and out:

    vmstat 1 10
    # procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
    #  r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
    #  2  1 812344  93120  10220 402312  1340 2210  1500  2300 1800 4100 12  9 40 39  0
    

    The columns to watch are si (KB/s swapped in) and so (swapped out). Sustained non-zero values in both, together with high wa (I/O wait) and low free, is thrashing: the working set no longer fits and the machine is spending its time moving pages instead of doing work. The fix is more RAM or less workload — not more swap.

    free -h only shows the total used; per-process swap use is in /proc/<pid>/status (VmSwap), or at a glance with smem (smem -s swap -r | head).

    Troubleshooting

    • swapon: /swapfile: read swap header failed — mkswap was never run, or the file was recreated after mkswap. Run sudo mkswap /swapfile again.
    • swapon: /swapfile: insecure permissions 0644, 0600 suggested — chmod 600 /swapfile. It still activates, but fix it.
    • swapon failed: Invalid argument — on Btrfs: missing chattr +C or compression on the subvolume (see above). On other filesystems: the file has holes; recreate it with dd instead of fallocate.
    • swapoff failed: Cannot allocate memory — not enough free RAM to absorb what is in swap. Add a bigger swap file first, then swapoff the old one; or stop the process using most of it.
    • Swap gone after reboot — no /etc/fstab entry, or a typo in it. sudo swapon -a reproduces the boot-time behaviour so you can see the error.
    • OOM kills despite free swap — the killed process may have been in a cgroup/container with its own memory limit (check dmesg for Memory cgroup out of memory), where host swap does not help unless the cgroup allows it.

    Summary

    1. swapon --show and free -h to see what you have.
    2. fallocate → chmod 600 → mkswap → swapon for a swap file; on Btrfs add chattr +C first (or use btrfs filesystem mkswapfile).
    3. Persist it in /etc/fstab and test with swapon -a before rebooting.
    4. Resize by recreating; swapoff needs free RAM to succeed.
    5. Set vm.swappiness to around 10 on application servers; consider zram on small or disk-slow machines.
    6. Watch vmstat's si/so — steady swapping means you need memory, not more swap.