Swap gets a bad reputation it doesn’t fully deserve. A lot of people hear “swap is being used” and immediately assume something’s wrong, when in reality a properly configured swap space is a normal, healthy part of memory management on most Linux systems — it’s really only a problem when the system is swapping heavily and continuously, not when a small amount sits there idle. swapon is the command that actually activates swap space so the kernel can use it, and understanding it properly means understanding what swap is for in the first place.
What swapon Does
swapon enables a device or file for use as swap space — additional virtual memory backed by disk (or, less commonly today, a fast SSD/NVMe device) that the kernel can move memory pages to when physical RAM is under pressure.
sudo swapon --show
On a system with no active swap, this returns nothing at all:
sudo swapon --show
(no output)
Checking the raw kernel-level view of active swap is done via /proc/swaps:
cat /proc/swaps
Filename Type Size Used Priority
An empty result under the header (as shown above) means no swap is currently active on this system — worth knowing, since not every Linux system has swap configured, particularly some container and cloud VM images.
Full Syntax and Options
swapon [options] [<spec>]
From swapon --help:
Options:
-a, --all enable all swaps from /etc/fstab
-d, --discard[=<policy>] enable swap discards, if supported by device
-e, --ifexists silently skip devices that do not exist
-f, --fixpgsz reinitialize the swap space if necessary
-o, --options <list> comma-separated list of swap options
-p, --priority <prio> specify the priority of the swap device
-s, --summary display summary about used swap devices (DEPRECATED)
-T, --fstab <path> alternative file to /etc/fstab
--show[=<columns>] display summary in definable table
--noheadings don't print table heading (with --show)
--raw use the raw output format (with --show)
--bytes display swap size in bytes in --show output
-v, --verbose verbose mode
The <spec> parameter:
-L <label> synonym for LABEL=<label>
-U <uuid> synonym for UUID=<uuid>
LABEL=<label> specifies device by swap area label
UUID=<uuid> specifies device by swap area UUID
PARTLABEL=<label> specifies device by partition label
PARTUUID=<uuid> specifies device by partition UUID
<device> name of device to be used
<file> name of file to be used
Basic Activation
sudo swapon /swapfile
or, for a dedicated swap partition:
sudo swapon /dev/sdb2
This activates a swap area that has already been formatted with mkswap (covered in a separate guide). Attempting to swapon a device or file that hasn’t been formatted with mkswap first will fail — the swap area needs a specific header signature the kernel checks for.
-a: Activate Everything in fstab
sudo swapon -a
Enables every swap entry listed in /etc/fstab. This is what runs automatically at boot; you generally only run it manually to re-enable swap after a swapoff -a without rebooting.
-p: Setting Priority
sudo swapon -p 10 /swapfile
sudo swapon -p 5 /dev/sdb2
When multiple swap areas are active, priority determines which one the kernel prefers. Higher numbers mean higher priority — the kernel fills higher-priority swap areas first. This matters when you have both a fast NVMe-backed swap and a slower disk-backed swap: giving the faster device a higher priority ensures it’s used first.
Swap areas with the same priority are used in a round-robin fashion, effectively striping swap writes across them — a technique sometimes used to get more swap throughput out of multiple slower disks combined.
-s / –show: Viewing Active Swap
swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 2G 0B -2
Columns:
| Column | Meaning |
|---|---|
| NAME | Path to the swap device or file |
| TYPE | partition or file |
| SIZE | Total size of the swap area |
| USED | Amount currently in use |
| PRIO | Priority value |
How Swap Actually Works Internally
When physical memory (RAM) fills up, the kernel’s memory management subsystem needs to free some pages to make room for new allocations. It does this through a process broadly called paging: it identifies pages that haven’t been accessed recently (using an approximation of a least-recently-used algorithm), and if those pages belong to anonymous memory (heap/stack data, not backed by a file already on disk), it writes them out to swap space to free up the physical RAM they were occupying. If that data is needed again later, the kernel reads it back in from swap (a page-in, or “swap-in”) — this is exactly what vmstat‘s si/so columns are measuring.
This is genuinely useful in a few real scenarios:
- Absorbing infrequent memory spikes without triggering the kernel’s Out-Of-Memory (OOM) killer, which forcibly terminates processes when memory is fully exhausted with no swap to fall back on.
- Hibernation (suspend-to-disk) — on desktop/laptop systems, the entire contents of RAM are written to a swap area so the machine can be fully powered off and later resumed exactly where it left off.
- Allowing overcommitted memory to function safely under
vm.overcommit_memorysettings that permit allocating more virtual memory than physically exists, relying on swap as a backstop.
Where it becomes a genuine problem: if a system relies heavily on continuous swapping under normal load (not just occasional bursts), performance degrades sharply, because disk (even fast SSD) is orders of magnitude slower than RAM for random access patterns. Sustained heavy swapping (“thrashing”) is a strong signal that the system needs more physical RAM or a workload adjustment, not more swap.
Creating and Activating a Swap File (Complete Workflow)
This is one of the most common real-world sysadmin tasks involving swapon, so it’s worth walking through end to end:
# 1. Create an empty file of the desired size (2GB example)
sudo fallocate -l 2G /swapfile
# 2. Restrict permissions before writing swap data into it
sudo chmod 600 /swapfile
# 3. Format it as swap
sudo mkswap /swapfile
# 4. Activate it
sudo swapon /swapfile
# 5. Confirm
swapon --show
free -h
To make this persist across reboots, add a line to /etc/fstab:
/swapfile none swap sw 0 0
Adjusting swappiness
A closely related tunable that affects how eagerly the kernel uses swap, separate from swapon itself:
cat /proc/sys/vm/swappiness
This value (0–100) controls the kernel’s preference for swapping anonymous memory out versus reclaiming page cache instead. A lower value (e.g., 10) makes the kernel more reluctant to swap, preferring to shrink cache first; a higher value makes it swap more readily. Server workloads sensitive to latency spikes often lower this from the common default of 60 down to something like 10–20.
sudo sysctl vm.swappiness=10
For a permanent change, add vm.swappiness=10 to /etc/sysctl.conf or a file under /etc/sysctl.d/.
zram: Compressed Swap in RAM
A modern variation worth knowing about, since it changes the usual disk-vs-RAM tradeoff entirely: zram creates a compressed block device that lives entirely in RAM and can itself be used as a swap target via mkswap/swapon, just like a regular disk-backed swap file.
sudo modprobe zram
echo 2G | sudo tee /sys/block/zram0/disksize
sudo mkswap /dev/zram0
sudo swapon -p 100 /dev/zram0
The idea is that compressing rarely-used memory pages and keeping them in RAM (rather than writing them out to genuinely slower disk storage) can be significantly faster than traditional swap, at the cost of some CPU time spent compressing and decompressing. This has become common on memory-constrained devices — many Android devices and some lightweight Linux desktop distributions enable zram swap by default — and it’s increasingly seen on servers too, sometimes configured as a higher-priority swap area layered in front of a traditional disk-backed swap file or partition as a fallback. Because zram swap is still swap from the kernel’s perspective, everything covered above about priority, swapon --show, and vmstat‘s si/so columns applies to it identically; it’s simply a different, RAM-resident block device sitting behind the same swapon interface.
Practical Sysadmin Use Cases
Adding emergency swap on a low-memory production box without a reboot:
sudo fallocate -l 1G /emergency_swap
sudo chmod 600 /emergency_swap
sudo mkswap /emergency_swap
sudo swapon /emergency_swap
Checking swap usage as part of a health-check script:
#!/bin/bash
used=$(free | awk '/Swap/ {print $3}')
total=$(free | awk '/Swap/ {print $2}')
if [ "$total" -gt 0 ] && [ "$used" -gt $((total / 2)) ]; then
echo "WARNING: swap usage above 50% (${used}/${total} kB)" | logger -t swap-check
fi
Prioritizing a fast NVMe swap device over a slower disk:
sudo swapon -p 100 /dev/nvme0n1p3
sudo swapon -p 10 /dev/sdb1
Watching Swap Come Under Pressure in Real Time
Beyond simply checking whether swap is active, it’s worth knowing how to watch it actually being exercised, since that’s the difference between “swap is configured” and “swap is actually helping (or hurting) right now.”
watch -n1 'free -h; echo; swapon --show'
Run alongside a memory-intensive task, this shows the USED column under swapon --show climbing in near real time as the kernel starts paging out anonymous memory. Cross-referencing this with vmstat 1‘s si/so columns confirms whether that swap usage is actively growing (high so, swap-out) or shrinking as pressure eases (high si, swap-in, as pages get pulled back into RAM once space frees up). A swap area that fills up once during a spike and then simply sits there, unused but occupied, until the next spike is completely normal and not a cause for concern — the concern case is continuous, simultaneous si and so activity, which indicates the system is thrashing, repeatedly paging the same data in and out under sustained pressure rather than settling.
Troubleshooting
swapon: /swapfile: swapon failed: Invalid argument→ the target hasn’t been formatted withmkswap, or its format doesn’t match what the kernel expects; runmkswapfirst.- Swap file on Btrfs won’t activate → Btrfs historically required special handling for swap files (Copy-on-Write needs to be disabled on the file with
chattr +Cbefore creation, plus specific kernel version support); check your distribution’s documentation, since this differs from ext4/xfs. - Swap doesn’t persist after reboot → confirm the corresponding line exists and is correct in
/etc/fstab. - High swap usage even with plenty of free RAM → check
vm.swappiness; a high value can cause the kernel to swap out idle pages proactively even when memory pressure isn’t severe.
Security Implications
Swap space can contain sensitive data that was in RAM at the time of swapping — passwords, cryptographic keys, or other secrets that an application held in memory. This is why:
- Swap files should always have restrictive permissions (
chmod 600) so only root can read them directly. - For systems handling especially sensitive data, encrypted swap (swap on top of LUKS/dm-crypt) is a real and fairly common hardening measure, ensuring that even if swap contents are recovered from disk later, they aren’t readable in plain text.
- Some security-sensitive applications explicitly
mlock()sensitive memory regions to prevent them from being swapped out at all.
swapon vs Related Commands
| Command | Purpose |
|---|---|
swapon | Activate a swap device or file |
swapoff | Deactivate a swap device or file |
mkswap | Format a device or file as swap space |
free | Quick summary of RAM and swap usage |
vmstat | Live swap activity rate (si/so columns) |
Compatibility Across Distributions
swapon is part of util-linux and behaves identically across Debian, Ubuntu, RHEL, Fedora, CentOS, Arch, and openSUSE. One area of real distribution difference: default swap configuration during installation varies — some distros default to a swap partition, others to a swap file, and some (particularly minimal cloud/container images) ship with no swap configured at all by default, leaving it to the administrator to add if desired.
Summary
swapon is the activation half of Linux’s swap mechanism — it tells the kernel “this device or file is now available as virtual memory backing store.” Understanding that some swap usage is normal and even beneficial, that priority and swappiness are real tuning knobs (not just on/off switches), and that swap contents deserve the same security consideration as the RAM they’re backing, turns swap from a vaguely understood “slow memory” concept into a properly managed part of your system’s memory strategy.
References
man 8 swaponman 8 mkswap- Linux kernel documentation on swap and memory management:
Documentation/admin-guide/mm/ man 5 proc(for/proc/swaps,/proc/sys/vm/swappiness)