Skip to content

Swap Files and Partitions

The previous articles covered how disks are organized (RAID, LVM, LUKS, filesystems) — all of it in service of storing persistent data. Swap serves a different purpose: it sits outside the filesystem, giving the system "backup memory" when RAM (physical memory) runs short. When RAM fills up, the kernel pushes less-used memory pages out to disk (swap), freeing RAM for active processes.

Swap comes after Filesystem Types, because swap is also disk space — as either a partition or a plain file — and configuring it is closely tied to the mechanisms covered in Mount and Umount and fstab. The difference is that swap isn't a filesystem: it doesn't store files, only temporarily holds memory pages.

What You Will Learn

By the end of this article you will be able to:

  • explain why swap exists and how its role has changed on modern systems;
  • distinguish between a swap partition and a swap file, and know when to choose which;
  • create and manage swap with mkswap and swapon/swapoff;
  • make swap permanent through /etc/fstab;
  • understand the swappiness parameter and tune it for a given situation;
  • explain the relationship between swap and the OOM killer, and judge whether swap is needed in a container/cloud environment.

Why Swap Is Needed

The kernel's memory manager continuously tracks every process's memory pages. When RAM isn't enough, the kernel "swaps out" pages that haven't been used in a while to disk-based swap space, freeing RAM for actively used processes. When a page is needed again later, it's brought back into RAM (swapped in).

Swap is useful in the following situations:

  • temporary RAM shortage — for example, extra headroom for an occasional heavy process (a backup, a compilation);
  • hibernation — the system writes the entire RAM state to disk and restores it later, which is only possible through swap;
  • avoiding the OOM killer — without swap, the kernel jumps straight to forcibly killing processes (an OOM kill) the moment RAM runs out; swap buys extra time and softens that transition.

Info

Swap isn't a full substitute for RAM — disk is thousands of times slower than RAM. Swap is meant for occasional memory pressure, not sustained, heavy use. If a system relies on swap constantly (called "thrashing"), performance drops sharply — the fix in that case is more RAM, not more swap.

Swap Partition vs. Swap File

Swap can take two forms: a dedicated disk partition (swap partition) or a special file inside an existing filesystem (swap file).

Criterion Swap partition Swap file
Creation Requires repartitioning the disk Created as an ordinary file in an existing filesystem
Resizing Difficult, usually needs repartitioning Easy — delete the file and recreate it at a different size
Performance Practically identical (the difference is negligible on modern kernels) Practically identical
Flexibility Low High — e.g. a cloud VM can add/remove swap without resizing the disk
Default choice Traditional server installs Modern distributions (Ubuntu 22.04+, and others) default to this

On a modern Linux kernel, the performance difference between the two is essentially nonexistent (some filesystems, such as btrfs, place special requirements on preparing a swap file). This is why most modern distribution installers default to a swap file, for its flexibility.

Creating a Swap Partition

Suppose /dev/sdb1 is an empty partition set aside for swap.

Danger

mkswap erases existing data on the disk (it converts the partition header to swap format). Run this command only on an empty, unused partition, ideally in a disposable test VM. Double-check the device name (lsblk, blkid) before applying this on a production disk.

1. Inspection (read-only)

lsblk
sudo blkid /dev/sdb1

Confirm the partition has no swap or other filesystem signature yet.

2. Preparing it as swap

sudo mkswap /dev/sdb1

This converts the partition to swap format and assigns it a UUID.

3. Activating it

sudo swapon /dev/sdb1

Checking:

swapon --show
free -h

swapon --show lists active swap devices, and free -h shows total and used swap.

Creating a Swap File

For a swap file, the disk isn't repartitioned — it's created as an ordinary file inside an existing filesystem.

1. Create the file and set its size

sudo fallocate -l 4G /swapfile

fallocate quickly allocates the requested size on disk. If the filesystem doesn't support fallocate (for example, in some btrfs configurations), dd is an alternative:

sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

2. Restrict permissions

sudo chmod 600 /swapfile

A swap file should never be readable by other users — otherwise sensitive data from memory (such as passwords) could be read back through the swap file on disk.

3. Prepare it as swap and activate it

sudo mkswap /swapfile
sudo swapon /swapfile

Checking:

swapon --show
free -h

Disabling Swap

sudo swapoff /dev/sdb1

or, for a swap file:

sudo swapoff /swapfile
sudo rm /swapfile

Warning

swapoff tries to move actively used swap pages back into RAM. If RAM doesn't have enough free space, swapoff can fail or the system can slow down temporarily. Before disabling swap, check with free -h how much swap is in use and whether RAM has room for it.

Making It Permanent Through /etc/fstab

Swap activated manually with swapon disappears after a reboot. To make it permanent, an entry is added to /etc/fstab.

For a swap partition, first find its UUID:

sudo blkid /dev/sdb1

/etc/fstab entry:

UUID=1234-5678-...  none  swap  sw  0  0

For a swap file, no UUID is needed — the file path is used directly:

/swapfile  none  swap  sw  0  0

Once the entry is added, to check it without rebooting:

sudo swapon -a
swapon --show

swapon -a activates every swap entry in /etc/fstab — letting you confirm a fstab entry is correct without rebooting. The fstab format and its relationship to mount/umount are covered in depth in fstab and Mount and Umount.

swappiness: Controlling When the Kernel Uses Swap

swappiness tells the kernel how eagerly to use swap, on a scale from 0 to 100:

  • near 0 — the kernel avoids swap as much as possible, using only RAM until it's nearly full;
  • near 100 — the kernel is inclined to actively use swap as soon as RAM gets even slightly busy.

Checking the current value:

cat /proc/sys/vm/swappiness

The default on most distributions is 60. Changing it temporarily (until reboot):

sudo sysctl vm.swappiness=10

For a permanent change, add it to /etc/sysctl.conf or a file under /etc/sysctl.d/:

vm.swappiness=10

Which value fits which environment:

Environment Recommended swappiness Reason
Database server Low (1–10) The database manages its own memory; swap adds latency
Desktop / everyday workstation Medium (30–60) A balance — rarely used programs go to swap, frequently used ones stay in RAM
High-memory server that rarely needs swap Low (10–20) Reduces latency, swap is reserved only for emergencies

Info

swappiness=0 doesn't disable swap entirely — it only pushes the kernel to reach for swap as a last resort. swapoff is what disables swap entirely.

Compressed Swap: zram and zswap

Modern systems increasingly avoid disk swap entirely by compressing memory instead. This comes up often for containers, VMs, and low-RAM machines.

  • zram creates a compressed block device in RAM and uses it as swap. Pages are compressed (typically 2–3×) rather than written to disk, so "swapping" stays at memory speed. Fedora and Ubuntu now enable it by default on many installs. It's genuine swap — swapon --show lists it — but backed by RAM, not disk.

    sudo modprobe zram
    zramctl                      # inspect zram devices
    

    In practice it's configured declaratively (systemd zram-generator, or the zram-tools package), not by hand.

  • zswap is different: it's a compressed cache in front of your real disk swap. Pages go into a compressed RAM pool first; only when that pool fills are the coldest pages written out to the actual swap device. So zswap complements a disk swap file, while zram usually replaces it.

Info

zram trades CPU (compression) for I/O (disk writes) — an excellent deal on cloud VMs and containers where RAM is the bottleneck and disk swap is slow or discouraged. It does not work for hibernation, which still requires a real disk-backed swap area at least the size of RAM.

Swap Priority

Multiple swap areas can be active at once, and the pri option controls the order they're used — higher priority first, equal priorities striped in parallel:

/dev/zram0   none  swap  sw,pri=100  0  0
/swapfile    none  swap  sw,pri=10   0  0

This is the standard way to prefer fast compressed zram swap and fall back to a slower disk swap file only under real pressure. Confirm the result with swapon --show, whose PRIO column reflects these values.

Swap and the OOM Killer

If both RAM and swap fill up, the kernel enters an "Out Of Memory" (OOM) state and triggers the OOM killer — it forcibly terminates the process using the most memory, or the "cheapest" one (lowest oom_score), to keep the system from crashing entirely.

Having swap delays the OOM killer and softens its effect: when RAM fills up, a process isn't killed immediately — less-active pages get swapped out first. With no swap, or very little, the OOM killer fires abruptly as soon as RAM runs out — which can cause unexpected process kills, especially during short-lived memory spikes (such as a build process).

dmesg | grep -i "out of memory"
journalctl -k | grep -i "oom"

These commands help find instances where the OOM killer fired, from the log entries.

Is Swap Needed in a Container or Cloud VM?

Swap isn't always needed — the right decision depends on the environment:

  • Containers (Docker, Kubernetes) — usually swap is disabled or managed through resource limits (memory limit). Kubernetes, for example, went a long time without supporting swap on nodes at all, since it can throw off resource accounting when swap is enabled (limited support has been added more recently, but it's used cautiously in production).
  • Cloud VMs (e.g. smaller instance types) — RAM can be limited, so adding a swap file is a cheap, quick fix; many providers recommend it.
  • Database servers — often run with little or minimal swap, since the database manages its own memory and disk latency hurts database performance.
  • A laptop/desktop that needs hibernation — swap (at least the size of RAM) is required, since hibernation writes the entire RAM state to swap.

Practical Scenario: Adding a Swap File to an Existing VM

Problem: on a production cloud VM, processes are occasionally being killed by the OOM killer due to memory shortage, but repartitioning the disk isn't an option (the cloud provider requires resizing the partition, which causes downtime).

1. Check the current state:

free -h
swapon --show
dmesg | grep -i "out of memory"

This confirms swap doesn't exist at all, and the OOM killer fired recently.

2. Check for free disk space:

df -h /

3. Create a 2 GiB swap file:

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

4. Verify:

free -h
swapon --show

5. Make it permanent:

/swapfile  none  swap  sw  0  0

This line is added to the end of /etc/fstab.

6. Tune swappiness to the server's workload:

sudo sysctl vm.swappiness=10

This value is written permanently into /etc/sysctl.d/99-swappiness.conf.

Result: the VM gained an extra 2 GiB of backup memory with no disk repartitioning. With swappiness=10, the kernel uses swap only when genuinely necessary, while reducing the likelihood of the OOM killer firing during temporary memory spikes.

Conclusion: a swap file provides a quick, reversible fix with no repartitioning — if a problem arises, it can be undone easily with swapoff and rm. But it isn't a permanent solution: if memory is consistently insufficient, the real fix is more RAM or optimizing the workload.

Common Mistakes

Leaving a Swap File World-Readable

If chmod 600 /swapfile isn't applied, other users may be able to read the swap file, which can contain sensitive data from memory (passwords, keys).

Forgetting fstab After swapon

Swap activated manually with swapon disappears on the next reboot — seeing it work and assuming the problem is solved is a mistake. A fstab entry is required for it to persist.

Treating Swap as a Permanent Fix for Insufficient RAM

Swap is a temporary reserve; relying on it continuously and heavily sharply degrades system performance (thrashing). Consistently high swap usage is a sign more RAM is needed, not a reason to add more swap.

Changing swappiness Without Checking First

Setting swappiness carelessly high on a sensitive service like a database can lead to unexpected latency. Changing it gradually, alongside monitoring, is recommended.

Exercises

  1. In a disposable VM, create a 1 GiB swap file, confirm it with swapon --show and free -h, then disable it with swapoff.
  2. Add a swap file entry to /etc/fstab and verify it with swapon -a without rebooting.
  3. Change vm.swappiness to 10 and then 80, and observe the difference through /proc/sys/vm/swappiness (a memory-consuming test program may be needed to see a real effect).
  4. Search dmesg or journalctl -k logs for instances where the OOM killer fired (if any) and identify which process was terminated.

Verification criterion: given a server's role (database, desktop, cloud VM needing hibernation), you should be able to recommend an appropriate swappiness value and justify it.

Summary

Swap provides temporary backup memory when RAM runs short — it can be a partition or a file, with a swap file more often recommended on modern systems for its flexibility. It's prepared with mkswap, managed with swapon/swapoff, and made permanent through /etc/fstab. The swappiness parameter tells the kernel when to use swap, and swap itself delays and softens the OOM killer — but it's deliberately disabled or kept minimal in containers and some database environments. How all these layers (RAID, LVM, LUKS, filesystem, swap) actually get mounted and connected automatically at boot continues in Mount and Umount and fstab.

References