mkswap doesn’t get much attention because it’s a “run once and forget” kind of command — you use it to set up swap space, and then you basically never think about it again. But understanding what it actually does (and why swap needs a special format at all, rather than just being a plain file) fills in a gap that a lot of the swap-related tooling (swapon, swapoff) assumes you already understand. This guide closes that gap and walks through the complete workflow of creating swap space properly.
What mkswap Does
mkswap sets up a Linux swap area on a device or in a file, writing the specific header/signature that the kernel requires before it will accept that space as valid swap via swapon.
mkswap --help
Usage:
mkswap [options] device [size]
Set up a Linux swap area.
Options:
-c, --check check bad blocks before creating the swap area
-f, --force allow swap size area be larger than device
-q, --quiet suppress output and warning messages
-p, --pagesize SIZE specify page size in bytes
-L, --label LABEL specify label
-v, --swapversion NUM specify swap-space version number
-U, --uuid UUID specify the uuid to use
-e, --endianness=<value> specify the endianness to use (native, little or big)
--verbose verbose output
--lock[=<mode>] use exclusive device lock (yes, no or nonblock)
-h, --help display this help
-V, --version display version
For more details see mkswap(8).
Why Swap Needs Formatting At All
This is worth understanding rather than just accepting: a swap area isn’t simply “an empty file the kernel writes memory pages into.” mkswap writes a specific header structure at the start of the target device or file, including a magic signature (SWAPSPACE2 on modern Linux swap format), a UUID, an optional label, and information about bad blocks to avoid (on physical devices where that applies). The kernel’s swapon system call checks for this exact signature before accepting the target as valid swap space — this is a safety mechanism, preventing you from accidentally telling the kernel to treat an arbitrary, non-swap-formatted device or file (which might contain a real filesystem with real data) as swap space, which would corrupt whatever was actually there.
Complete Workflow: Creating a Swap File
This is the most common real-world use case, so let’s walk through it fully.
# Step 1: create a file of the desired size
sudo fallocate -l 2G /swapfile
fallocate is the fast, modern way to preallocate a file of a given size without actually writing zeros through it byte by byte (which dd would do, more slowly). If fallocate isn’t supported on your target filesystem (some older or unusual filesystem types don’t support it), fall back to:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
# Step 2: restrict permissions before writing swap data into it
sudo chmod 600 /swapfile
This matters for security, covered further below — swap can contain sensitive data paged out from RAM, so the file shouldn’t be world-readable.
# Step 3: format it as swap
sudo mkswap /swapfile
Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=a1b2c3d4-e5f6-7890-abcd-ef1234567890
# Step 4: activate it
sudo swapon /swapfile
# Step 5: verify
swapon --show
free -h
To make it persistent across reboots, add a line to /etc/fstab:
/swapfile none swap sw 0 0
Creating Swap on a Dedicated Partition
If you have a dedicated partition set aside for swap (a traditional approach, still common, especially outside cloud environments), the process is nearly identical, just skip the file-creation steps:
sudo mkswap /dev/sdb2
sudo swapon /dev/sdb2
Add the corresponding line to /etc/fstab, ideally referencing the partition by UUID rather than device name for stability across reboots:
sudo blkid /dev/sdb2
/dev/sdb2: UUID="a1b2c3d4-e5f6-7890-abcd-ef1234567890" TYPE="swap"
UUID=a1b2c3d4-e5f6-7890-abcd-ef1234567890 none swap sw 0 0
Key Options Explained
-c: Check for Bad Blocks
sudo mkswap -c /dev/sdb2
Scans the target device for bad blocks before creating the swap area, marking them to be avoided. This is genuinely more relevant on older or aging physical disks than on modern SSDs (which handle bad-block remapping transparently at the firmware/controller level), but it’s a reasonable precaution on hardware you’re not fully confident in.
-L: Setting a Label
sudo mkswap -L myswap /swapfile
Assigns a human-readable label to the swap area, which lets you reference it in /etc/fstab and swapon commands via LABEL=myswap instead of a raw path or UUID — useful in setups where device paths might not be stable.
-U: Specifying a UUID
sudo mkswap -U a1b2c3d4-e5f6-7890-abcd-ef1234567890 /dev/sdb2
Normally mkswap generates a random UUID automatically; this lets you specify one explicitly, which is occasionally useful in scripted/templated provisioning setups where you need a predictable, known UUID ahead of time (for example, baking a golden VM image where the fstab entry is pre-written to reference a specific UUID).
-p: Page Size
sudo mkswap -p 4096 /swapfile
Specifies the page size used, in bytes. This should generally match your system’s actual memory page size (commonly 4096 bytes/4KB on most x86_64 systems, though some architectures like certain ARM configurations use larger page sizes) — mismatches here aren’t typically something you need to touch manually, since mkswap defaults to detecting this correctly for your running kernel.
-f: Force
sudo mkswap -f /dev/sdb2 1G
Allows creating a swap area larger than what’s specified as available, or overrides certain safety checks. Use cautiously, and only when you’re confident about the target device’s real capacity.
How This Interacts with swapon
It’s worth being explicit about the relationship: mkswap only formats the space — it does not activate it. You always need swapon afterward to actually bring it into use, and swapoff later if you want to deactivate it (both covered in their own dedicated guides in this series). A common beginner mistake is running mkswap and expecting swap to be immediately active — checking swapon --show or free -h right after mkswap alone will still show no active swap until swapon is run.
Practical Sysadmin Examples
Full provisioning script for adding swap to a fresh cloud VM (common on minimal cloud images with no default swap):
#!/bin/bash
set -e
SWAPFILE=/swapfile
SIZE=2G
if swapon --show | grep -q "$SWAPFILE"; then
echo "Swap already active, exiting."
exit 0
fi
fallocate -l "$SIZE" "$SWAPFILE"
chmod 600 "$SWAPFILE"
mkswap "$SWAPFILE"
swapon "$SWAPFILE"
echo "$SWAPFILE none swap sw 0 0" >> /etc/fstab
echo "Swap file created and activated: $SIZE"
Resizing swap (shrink or grow) — requires recreating it:
sudo swapoff /swapfile
sudo rm /swapfile
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Labeling swap for stable reference in fstab across a fleet of similarly-provisioned servers:
sudo mkswap -L swap0 /dev/sdb1
LABEL=swap0 none swap sw 0 0
How Much Swap Should You Actually Create?
mkswap doesn’t have an opinion about sizing — it’ll happily format whatever size file or partition you point it at — but choosing the right size is a real decision worth thinking through rather than picking an arbitrary number.
The old-school rule of thumb (“swap should be 2x your RAM”) largely comes from an era when hibernation-to-disk was a common requirement and RAM sizes were small; it’s mostly outdated for modern server workloads with tens of gigabytes of RAM. A more current, practical set of guidelines:
- Systems with less than 2GB RAM — swap roughly equal to or somewhat larger than RAM, since these systems are the most likely to hit genuine memory pressure under normal use.
- Systems with 2–16GB RAM — swap in the range of the same size as RAM, or somewhat less, mainly as a safety buffer for occasional spikes rather than routine use.
- Systems with more than 16GB RAM — a smaller, fixed amount (commonly somewhere in the 2–8GB range) is often sufficient, purely as an emergency buffer against unexpected spikes and to give the kernel’s OOM-avoidance mechanisms room to work, rather than scaling swap linearly with increasingly large RAM sizes.
- Systems intending to use hibernation (suspend-to-disk) — swap needs to be at least as large as physical RAM, since the entire memory contents get written there during hibernation; this consideration mostly applies to laptops and desktops, rarely to servers.
Cloud provider default images vary widely on this — many ship with zero swap configured at all by default, leaving it to the administrator to decide, which is exactly the gap the provisioning workflow earlier in this guide is meant to fill.
Multiple Swap Areas and Striping
A detail worth knowing if you’re working with several available disks: you’re not limited to a single swap area. Creating and activating multiple swap files or partitions, especially at the same priority level, lets the kernel effectively stripe swap writes across them, increasing aggregate swap throughput compared to relying on a single device.
sudo mkswap /dev/sdb1
sudo mkswap /dev/sdc1
sudo swapon -p 10 /dev/sdb1
sudo swapon -p 10 /dev/sdc1
With both set to the same priority, the kernel distributes swap activity across them in a round-robin fashion rather than filling one completely before touching the other — a technique occasionally used on systems with multiple modest-speed disks where no single device offers enough swap throughput alone.
Troubleshooting
mkswap: error: /swapfile is mounted; will not make swapspace→ you’re trying to format a filesystem image or device that’s currently mounted as a regular filesystem elsewhere; that’s not a valid swap target.swaponfails aftermkswapsucceeded → double check you’re referencing the exact same path/device; also confirm the file wasn’t created with a sparse hole that a copy-on-write filesystem (Btrfs, some configurations of XFS with reflink) mishandles — Btrfs specifically needschattr +C(disabling copy-on-write) on the file beforemkswap/swaponwill work correctly.- Insufficient disk space during
fallocate→ checkdf -hon the target filesystem before starting; a swap file needs genuinely free space, it’s not compressible or shrinkable after creation. - Swap file works but performs poorly → confirm it’s not sitting on a network-mounted or otherwise slow filesystem; swap performance is extremely sensitive to underlying storage latency.
Performance Considerations
Swap file performance depends heavily on the underlying storage — an SSD/NVMe-backed swap file performs dramatically better under actual paging load than one on a spinning disk, simply because swap activity tends to involve latency-sensitive random access patterns, which spinning disks handle poorly. If a workload genuinely depends on swap being used regularly (not just as an emergency buffer), prioritize placing that swap on your fastest available storage.
Security Implications
As covered in the swapon guide, swap space can contain sensitive data paged out from process memory — this is exactly why the file permission step (chmod 600) immediately after creating the swap file matters, before any data is ever written to it. For environments handling particularly sensitive data, consider setting up swap on top of an encrypted block device (LUKS/dm-crypt) from the start, rather than relying solely on file permissions, since file permissions only protect against other unprivileged users on the same running system — they don’t protect data at rest if the physical disk itself is later accessed directly (e.g., removed and read on another machine).
mkswap vs Related Commands
| Command | Purpose |
|---|---|
mkswap | Format a device or file with the swap area header, preparing it for use |
swapon | Activate a formatted swap area |
swapoff | Deactivate an active swap area |
fallocate / dd | Create the underlying file that mkswap will then format |
blkid | Confirm a device/file’s UUID and detected type after formatting |
Compatibility Across Distributions
mkswap is part of util-linux and behaves identically across Debian, Ubuntu, RHEL, Fedora, CentOS, Arch, and openSUSE — the swap format itself is a kernel-level standard, not distribution-specific. The one real compatibility wrinkle worth remembering is filesystem-specific: Btrfs requires the extra chattr +C step to disable copy-on-write on a swap file before it will function correctly, which isn’t needed on ext4 or xfs.
Summary
mkswap is a small, single-purpose command — write the header that tells the kernel “this is valid swap space” — but understanding why that header exists (as a safety mechanism against accidentally swapping onto real data) makes the whole swap-creation workflow make sense: mkswap to format, swapon to activate, permissions set correctly before anything sensitive ever touches it, and an /etc/fstab entry if it needs to survive a reboot.
References
man 8 mkswapman 8 swaponman 8 swapoff- Linux kernel documentation on swap:
Documentation/admin-guide/mm/