Linux Swap: Create Swapfile, Swap Partition, zram and zswap

Linux Swap: Create Swapfile, Swap Partition, zram and zswap

✅ Tested on Ubuntu 26.04 LTS, Debian 12, and Arch Linux — Last updated: June 2026

Linux swap is disk space used as an overflow when RAM fills up. The kernel moves inactive memory pages to swap to free up RAM for active processes. Without swap, the out-of-memory (OOM) killer terminates processes when RAM runs out. This guide covers the two swap types (swapfile and swap partition), how to create them, the swappiness kernel parameter, zswap and zram for compressed swap, and how much swap to configure for different workloads.

Contents
  1. Check Current Swap
  2. Create a Swapfile
  3. Create a Swap Partition
  4. How Much Swap Do You Need
  5. Swappiness Setting
  6. Disable Swap
  7. Multiple Swap Areas
  8. zswap: Compressed Swap Cache
  9. zram: Swap in RAM
  10. Monitor Swap Usage
  11. Swap on SSDs
  12. Troubleshooting
  13. Frequently Asked Questions
    1. Should I use swap on a server with lots of RAM?
    2. What's better: zram, zswap, or a swapfile?
    3. Further Reading

Check Current Swap

# Show all swap areas:
swapon --show
# NAME       TYPE  SIZE  USED  PRIO
# /swapfile  file    4G  512M    -2

# Show memory and swap summary:
free -h
#              total   used   free  shared  buff/cache  available
# Mem:          15Gi   8.2Gi  2.1Gi  456Mi     4.9Gi      6.4Gi
# Swap:          4Gi   512Mi  3.5Gi

# Detailed view from /proc:
cat /proc/swaps
cat /proc/meminfo | grep -i swap

Create a Swapfile

A swapfile is a regular file on your filesystem used as swap. It's the most flexible option — easy to resize and doesn't require a dedicated partition.

# Step 1: Create the swapfile (4 GB example):
sudo fallocate -l 4G /swapfile

# If fallocate fails (some filesystems like Btrfs don't support it):
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress

# Step 2: Set correct permissions (root read/write only):
sudo chmod 600 /swapfile

# Step 3: Format as swap:
sudo mkswap /swapfile
# Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)

# Step 4: Enable the swap:
sudo swapon /swapfile

# Verify:
swapon --show
free -h
# Step 5: Make it permanent (survives reboot):
# Add to /etc/fstab:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Verify the fstab entry:
cat /etc/fstab | grep swap

Create a Swap Partition

A dedicated swap partition is slightly faster than a swapfile and required for hibernation (suspend-to-disk) on most systems.

# List disks and partitions:
lsblk
fdisk -l

# Create swap partition with fdisk (example on /dev/sdb):
sudo fdisk /dev/sdb
# n → new partition
# p → primary
# (accept defaults for start/end or specify size)
# t → change type → 82 (Linux swap)
# w → write

# Format partition as swap:
sudo mkswap /dev/sdb1
# Setting up swapspace version 1, size = 4 GiB

# Enable:
sudo swapon /dev/sdb1

# Make permanent using UUID (more reliable than device name):
sudo blkid /dev/sdb1
# /dev/sdb1: UUID="abc123-..." TYPE="swap"

# Add to /etc/fstab with UUID:
echo 'UUID=abc123-... none swap sw 0 0' | sudo tee -a /etc/fstab

How Much Swap Do You Need

ScenarioRecommended swapReason
Desktop, 8+ GB RAM2-4 GBSafety net for memory spikes
Desktop, 4 GB RAM4-8 GBLow RAM needs meaningful overflow
Server, no hibernation1-2x RAM (up to 8 GB max)Buffer for unexpected spikes
Hibernation requiredRAM + 10-20%Must fit entire RAM contents
VPS, 1-2 GB RAM2-4 GBPrevents OOM kills on cheap VPS
High RAM (64 GB+)4-8 GBEnough for OOM safety, don't over-allocate
Docker/containers2x RAM or noneContainers handle OOM differently

Old advice said "swap = 2x RAM" but with modern systems having 16-64 GB of RAM, 2x becomes excessive. On a 32 GB RAM machine, 4-8 GB of swap is plenty. The goal is to handle occasional spikes, not replace RAM.

Swappiness Setting

Swappiness controls how aggressively the kernel moves memory pages to swap. The value ranges from 0 to 200 (kernel 5.8+) or 0 to 100 (older kernels).

# Check current swappiness:
cat /proc/sys/vm/swappiness
# Default: 60

# What the values mean:
# 0   = swap only when absolutely necessary (avoid for most systems)
# 10  = prefer RAM strongly, swap only under pressure
# 60  = default — balanced
# 100 = swap aggressively (prefer to keep file cache in RAM)
# 200 = (kernel 5.8+) aggressive zswap usage

# Change temporarily (resets on reboot):
sudo sysctl vm.swappiness=10

# Change permanently:
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl -p /etc/sysctl.d/99-swappiness.conf
System typeRecommended swappiness
Desktop workstation10-30 (keep interactive performance)
Database server (PostgreSQL, MySQL)1-10 (databases manage their own caching)
General web server10-20
Memory-constrained VPS10-30 (use swap to survive spikes)
SSD-based system10-20 (SSD can handle more swap)

Disable Swap

# Disable swap immediately:
sudo swapoff -a    # disable ALL swap areas
sudo swapoff /swapfile    # disable specific swapfile

# Re-enable all swap from /etc/fstab:
sudo swapon -a

# Permanently disable (comment out fstab entry):
sudo nano /etc/fstab
# Comment out swap line:
# #/swapfile none swap sw 0 0

# Note: Kubernetes requires swap disabled:
sudo swapoff -a
# Comment out in /etc/fstab to persist after reboot

Multiple Swap Areas

# Linux can use multiple swap areas simultaneously
# Priority controls which is used first (higher number = higher priority)

# Add second swap with priority:
sudo swapon --priority 10 /swapfile
sudo swapon --priority 5 /dev/sdb1

# View priorities:
swapon --show
# NAME        TYPE  SIZE  USED  PRIO
# /swapfile   file    4G   0B     10   ← used first
# /dev/sdb1   part    8G   0B      5   ← used when first is full

# /etc/fstab with priorities:
/swapfile   none  swap  sw,pri=10  0  0
/dev/sdb1   none  swap  sw,pri=5   0  0

zswap: Compressed Swap Cache

zswap is a kernel feature that intercepts pages headed to swap and compresses them first, storing them in a small pool of RAM. Only if the compressed pool fills does it write to disk swap. This dramatically reduces swap I/O and speeds up swap-heavy workloads.

# Check if zswap is enabled:
cat /sys/module/zswap/parameters/enabled
# Y = enabled, N = disabled

# Enable zswap at runtime:
echo 1 | sudo tee /sys/module/zswap/parameters/enabled

# Enable zswap permanently (add to kernel command line):
sudo nano /etc/default/grub
# Add to GRUB_CMDLINE_LINUX_DEFAULT:
# zswap.enabled=1 zswap.compressor=lz4 zswap.max_pool_percent=20

sudo update-grub

# Check zswap statistics:
grep -r . /sys/kernel/debug/zswap/
# pool_limit_hit:     0
# reject_alloc_fail:  0
# written_back_pages: 1024    ← pages that had to go to disk swap
# stored_pages:       8192    ← pages compressed in zswap pool

zram: Swap in RAM

zram creates a compressed RAM device used as swap — no disk involved at all. It's excellent for systems where disk I/O is the bottleneck or for small VPS instances with slow disks.

# Ubuntu 24.04+ and Fedora enable zram by default
# Check:
zramctl
# NAME       ALGORITHM DISKSIZE  DATA  COMPR TOTAL STREAMS MOUNTPOINT
# /dev/zram0 lz4           4G   1.2G  400M  500M       4 [SWAP]

# Install zram-tools manually (Ubuntu/Debian):
sudo apt install zram-tools -y

# Configure /etc/default/zramswap:
sudo nano /etc/default/zramswap
# ALGO=lz4
# PERCENT=50    # use 50% of RAM as compressed swap

# Restart:
sudo systemctl restart zramswap

# Manual zram setup:
# Load kernel module:
sudo modprobe zram

# Create 4GB zram device:
echo 4G | sudo tee /sys/block/zram0/disksize

# Format and enable:
sudo mkswap /dev/zram0
sudo swapon /dev/zram0 --priority 100    # high priority = used before disk swap

Monitor Swap Usage

# Real-time memory and swap:
watch -n 1 free -h

# Per-process swap usage:
for pid in /proc/*/status; do
  awk '/VmSwap|Name/{printf $2 " " $3 "n"}' $pid
done 2>/dev/null | sort -k2 -n -r | head -20

# Or use smem:
sudo apt install smem -y
smem -r | head -20    # sorted by swap usage

# Which processes use most swap:
ps aux --sort=-%mem | awk '{print $1,$2,$4,$11}' | head -20

# vmstat for swap I/O (si/so columns):
vmstat 1
# procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
#  r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
#  1  0   1024 2048000  51200 4096000   0    0     0     0  500  800 5  1 94  0  0
# si = swap in (pages/s from swap to RAM)
# so = swap out (pages/s from RAM to swap)
# High si/so values indicate excessive swapping (needs more RAM)

Swap on SSDs

Using swap on an SSD is fine with modern SSDs. The write wear concern is mostly theoretical for desktop usage — swap activity is low on systems with adequate RAM. A few practical notes:

  • Use a swapfile, not a partition — easier to manage and modern filesystems handle it efficiently
  • Lower swappiness to 10 — reduces unnecessary swap usage and extends SSD life marginally
  • NVMe SSDs — swap on NVMe is nearly as fast as RAM for small working sets. zswap/zram matter less here
  • Enable TRIMsudo systemctl enable fstrim.timer — keep the SSD healthy regardless of swap
  • Don't use swap on eMMC — cheap eMMC storage in Raspberry Pis and netbooks has very limited write endurance. Use zram instead

Troubleshooting

ProblemDiagnosticFix
Out of memory kills (OOM)dmesg | grep -i oomAdd more swap or increase RAM
System very slow, high swap usagevmstat 1 — high si/soFind memory leak with smem, add RAM, lower swappiness
swapon: device busyCheck swapon --showAlready active, or another process holds it
fstab entry not activating swapBoot logs: journalctl -b | grep swapCheck UUID matches blkid output
fallocate fails on BtrfsFilesystem type checkUse dd instead of fallocate for Btrfs
Kubernetes won't startkubectl describe nodeDisable swap: swapoff -a and remove from fstab
# Check if OOM killer has triggered:
dmesg | grep -i "out of memory"
dmesg | grep -i "oom-kill"
journalctl -b | grep -i oom

# See what the OOM killer killed:
dmesg | grep "Killed process"

# Emergency: free up swap immediately:
sudo swapoff -a && sudo swapon -a    # flushes swap back to RAM
# (Only works if you have enough free RAM)

Frequently Asked Questions

Should I use swap on a server with lots of RAM?

Yes, even with 32-64 GB of RAM. Swap serves as a safety buffer for unexpected spikes and prevents OOM kills during brief memory pressure. Keep it small (4-8 GB) and set swappiness to 1-10 so the kernel only uses it in emergencies, not for routine memory management. A server that hits swap occasionally is much better than one that OOM-kills processes. The only exception is Kubernetes nodes, which require swap disabled because container memory limits don't account for swap usage correctly.

What's better: zram, zswap, or a swapfile?

Use all three in layers: zram as the primary swap (compressed, in RAM, no disk I/O), zswap as an intermediate cache before hitting disk, and a small swapfile as the last resort for when everything fills up. On modern Ubuntu (22.04+), zram is enabled by default alongside a swapfile — this is a sensible default. For RAM-constrained VPS instances (1-2 GB), zram alone with a small swapfile is ideal. For desktop systems with 16 GB+ RAM, a simple swapfile with low swappiness is sufficient.

Swap configuration intersects with other resource management. Our process management guide covers the OOM killer and setting memory limits with cgroups. For database servers where swap tuning matters most, our PostgreSQL setup guide covers memory configuration including vm.swappiness=1 and huge pages. The disk management guide covers partitioning if you want a dedicated swap partition.


Go up