Configure and manage swap space in Linux

How to configure and manage swap space in Linux

We may earn an affiliate commission through purchases made from our guides and tutorials.

Most Linux servers run just fine with RAM alone until they do not. When processes briefly spike or a database needs extra working room, the kernel can borrow disk as “swap” to avoid out-of-memory kills. On small VPS instances, especially fresh Droplets, enabling and tuning swap smooths over transient peaks and buys you time to scale. The steps below work on recent Ubuntu, Debian, Rocky, AlmaLinux, and RHEL systems and assume you have shell access with sudo.

What swap does

Swap extends virtual memory by paging inactive memory pages to disk. The kernel prefers RAM for hot pages and uses swap for cold ones. As noted later in the tuning section, you control this behavior with vm.swappiness. Properly sized swap prevents abrupt process termination under load, but it is slower than RAM. The goal is stability first, speed second, with monitoring to catch chronic memory pressure early.

When and how much

Use swap when your workload has bursty memory demand or when you want a cushion against unexpected growth. On RAM-constrained nodes, a modest swap file often improves uptime during deploys, compiles, or batch jobs. A practical starting point is 25–50% of RAM for servers with ≥4 GB, up to 1–2× RAM on tiny instances, with an absolute cap that matches your performance tolerance. If you plan to hibernate laptops, match swap to RAM; servers rarely hibernate. We will size conservatively and adjust as you observe behavior.

Modern distributions prefer a swap file over a dedicated partition because it is simpler to grow or shrink. Filesystems like ext4 and XFS support swap files safely on current kernels. Unless you have special constraints, use a swap file. If you already have a swap partition, you can keep it and still add a swap file for extra headroom, using priority to control usage.

Create a swap file

Create the file with secure permissions, mark it as swap, enable it, and make the change persistent.

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

Verify that the system sees it.

swapon --show
free -h

Persist the change across reboots by adding an /etc/fstab entry.

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

If fallocate reports that it cannot allocate a contiguous file or you prefer to zero the space, use dd instead.

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Tune kernel behavior

Two sysctl parameters control how aggressively the kernel uses swap and how it reclaims cached filesystem metadata. Start conservatively, then adjust based on monitoring.

cat <<EOF | sudo tee /etc/sysctl.d/99-swap-tuning.conf
vm.swappiness = 10
vm.vfs_cache_pressure = 50
EOF
sudo sysctl --system

Lower vm.swappiness (for example, 1–20) favors RAM, which is typical for servers with headroom. Higher values (40–60) can help desktop-like workloads where keeping page cache is valuable under pressure. As noted earlier, the goal is to avoid OOM while minimizing unnecessary paging.

Adjust priorities and multiple swap areas

When more than one swap area exists, the kernel uses priorities to decide order. Higher numbers take precedence. This lets you prefer faster devices or zram while keeping disk swap as overflow.

sudo mkswap -L fastswap /swapfile
sudo swapon -p 100 /swapfile

Persist a priority in /etc/fstab with the pri= option.

/swapfile none swap sw,pri=100 0 0

Check the result.

cat /proc/swaps

Resize or remove swap

To change size, turn swap off, resize the file, remake the swap header, turn it back on, and update /etc/fstab if the path did not change. This is fast on filesystems that support hole punching.

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

To shrink with dd, recreate and reinitialize.

sudo swapoff /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

To remove swap entirely, disable it and clean up.

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

Add a swap partition (optional)

A dedicated partition can offer predictable layout and is common on older installations. Identify free space, create the partition, and label it.

sudo fdisk /dev/vda

Inside fdisk, create a new partition of type 82 (Linux swap), write, then format and enable it.

sudo mkswap /dev/vda3
sudo swapon /dev/vda3

Persist with its UUID to avoid device renumbering issues.

UUID=$(blkid -s UUID -o value /dev/vda3)
echo "UUID=$UUID none swap sw,pri=60 0 0" | sudo tee -a /etc/fstab

Use compressed RAM with zram

zram creates a compressed in-memory block device used as swap. It is much faster than disk swap and reduces I/O at the cost of CPU. Pair it with a small disk swap file as overflow.

On Ubuntu and Debian, enable the packaged service.

sudo apt update
sudo apt install zram-tools

Edit /etc/default/zramswap to set the size fraction of RAM and the compression algorithm, then restart.

sudo sed -i 's/^#*PERCENT=.*/PERCENT=50/' /etc/default/zramswap
sudo systemctl restart zramswap
swapon --show --summary

On RHEL-like systems, use zram-generator. Create a config file and start it.

sudo dnf install zram-generator
cat <<'EOF' | sudo tee /etc/systemd/zram-generator.conf
[zram0]
zram-size = ram / 2
compression-algorithm = zstd
EOF
sudo systemctl daemon-reload
sudo systemctl start systemd-zram-setup@zram0
swapon --show

As mentioned in the priority section, give zram a higher priority than disk swap so the kernel prefers it.

Encrypt swap for sensitive workloads

If you handle confidential data and cannot rely on full-disk encryption, encrypt swap to reduce the risk of data remnants. Ephemeral swap keys are typical on servers.

On Ubuntu, enable an encrypted swap device with a random key.

sudo apt install cryptsetup
echo 'CRYPTSETUP=y' | sudo tee /etc/cryptsetup-initramfs/conf-hook

Configure /etc/crypttab and fstab.

echo 'cryptswap1 /swapfile /dev/urandom swap,cipher=aes-xts-plain64,size=256' | sudo tee -a /etc/crypttab
echo '/dev/mapper/cryptswap1 none swap sw 0 0' | sudo tee -a /etc/fstab
sudo update-initramfs -u
sudo systemctl daemon-reload
sudo swapoff -a && sudo swapon -a

Confirm the mapping.

lsblk -e7

If your disk is already fully encrypted, a plain swap file within that volume is usually sufficient.

Monitor usage and pressure

Watch memory, swap activity, and reclaim pressure. Spot trends rather than single spikes.

free -h
vmstat 5

Use pressure-stall-information (PSI) where available to quantify sustained memory pressure.

cat /proc/pressure/memory

For live systems, expose these metrics to your monitoring stack and alert on thresholds. A useful pattern is “swap used >25% and memory PSI >0.1 for 5 min,” which suggests persistent pressure rather than incidental paging. As we emphasized earlier, swap should protect stability; sustained use means you should right-size RAM or optimize applications.

Troubleshoot common issues

If swapon fails on a file, check permissions and attributes. The file must be owned by root, mode 600, and not sparse in an unsupported way.

sudo chown root:root /swapfile
sudo chmod 600 /swapfile

If /etc/fstab hangs at boot, you may have a bad entry. Comment it out and reapply carefully.

sudo sed -i 's|^\(/swapfile.*\)$|# \1|' /etc/fstab

If performance drops after enabling swap, reduce vm.swappiness, prefer zram, and verify that your application is not overcommitting. In containers, be aware that cgroup memory limits interact with host swap; heavy paging inside a constrained cgroup can still trigger OOM kills if limits are strict.

Practical defaults for a small Droplet

For a 1–2 GB RAM Droplet, start with a 1–2 GB zram device and a 1–2 GB disk-backed swap file. Set vm.swappiness=10 and vm.vfs_cache_pressure=50. Give zram a higher priority and keep the disk swap as overflow. Watch metrics for a week and adjust. Because you are on SSD-backed storage, disk swap is acceptable for rare bursts, but aim to keep usage low most of the time.

# Ubuntu quick start
sudo apt update
sudo apt install zram-tools
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swap-tuning.conf
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.d/99-swap-tuning.conf
sudo sysctl --system
sudo sed -i 's/^#*PERCENT=.*/PERCENT=50/' /etc/default/zramswap
sudo systemctl restart zramswap
sudo fallocate -l 2G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile
echo '/swapfile none swap sw,pri=10 0 0' | sudo tee -a /etc/fstab
sudo swapon -a && swapon --show

Maintenance and next steps

Revisit swap sizing after notable workload changes, kernel upgrades, or database growth. Keep your choices documented alongside your server’s build notes so future changes are deliberate. If you notice regular swap growth or elevated memory pressure, plan either an application optimization pass or a RAM upgrade. As referenced at the outset, swap is a safety net; use it to keep services steady while you address root causes.

Was this helpful?

Thanks for your feedback!
Alex is the resident editor and oversees all of the guides published. His past work and experience include Colorlib, Stack Diary, Hostvix, and working with a number of editorial publications. He has been wrangling code and publishing his findings about it since the early 2000s.

Leave a comment

Your email address will not be published. Required fields are marked *