VMware ESXi and vSphere Cluster Management

Linux Swap Partitions and the swapon Command

Learn how Linux swap works, how it relates to RAM and virtual memory, and how to inspect, enable, disable, size, and persist swap safely.

Swap is disk-backed space that the Linux kernel can use as part of virtual memory. It provides additional backing storage when physical memory is under pressure, but it is not a replacement for RAM. This lesson explains swap partitions, swap files, the swapon command, persistent configuration, sizing, and troubleshooting.

What Is Swap?

RAM is fast, volatile physical memory used by running programs and the operating system. A memory page is a fixed-size unit of memory that the kernel manages. When RAM becomes pressured, Linux can write less recently used pages to configured swap space. This process is commonly called swapping or paging.

Swap can be provided by:

  • A swap partition: a dedicated disk partition initialized with the Linux swap format.
  • A swap file: a regular file configured for use as swap.

Swap is supplementary backing storage. Storage is much slower than RAM, so adding swap does not give applications RAM-like performance. Its value is that it can provide memory headroom and help the kernel avoid immediate allocation failures during temporary pressure.

RAM, Virtual Memory, and Swap

Virtual memory is the memory-management model that gives processes their address spaces and lets the kernel manage RAM together with backing storage. An active program normally needs its currently used pages in RAM. Pages that have not been used recently may be moved from RAM to swap.

  1. A program accesses memory pages while running.
  2. RAM pressure increases because applications, the kernel, and caches need memory.
  3. The kernel may write less recently used pages to swap, freeing RAM for more active pages.
  4. If a swapped page is needed again, the kernel reads it back into RAM. This is a page-in operation.

Linux may use some swap before RAM is completely full. The exact behavior depends on kernel memory-management policy and workload. A small amount of swap usage is not automatically a problem, especially if the pages are rarely accessed.

CharacteristicRAMSwap partition or swap file
Storage mediumPhysical memory modulesDisk or other block storage
Typical speedVery fast, with low latencyMuch slower; SSDs are generally faster than HDDs, but both are slower than RAM
VolatilityVolatile; contents are lost when power is removedNonvolatile storage while the device remains available
Role in memory managementPrimary working memory for active pagesBacking storage for pages moved out of RAM
Performance impact when heavily usedNormal application operationFrequent paging can slow applications and make the system unresponsive

When Does Swapping Occur?

Memory pressure occurs when the system has less readily available RAM than the current workload needs. This can happen when many programs run at once, one process allocates unusually large amounts of memory, or file and kernel caches compete with applications.

Linux can move pages to swap as part of its memory-management policy even before all RAM appears completely exhausted. What matters operationally is not merely whether swap is configured or has any used capacity, but whether paging is frequent and affecting performance.

Sustained growth in swap usage, high paging activity, and slow application response can indicate:

  • Insufficient RAM for the workload.
  • An oversized application or workload.
  • A process with a memory leak or unexpectedly high memory consumption.
  • A memory-management or capacity-planning issue.

Performance and Swap Thrashing

RAM has far lower latency and much higher practical throughput than disk storage. HDDs are especially slow for the random reads and writes involved in paging. SSDs reduce the delay, but they still do not perform like RAM.

Swap thrashing is severe repeated paging: the kernel continually writes pages to swap and reads other pages back into RAM. Storage I/O consumes system resources while applications wait for their data. The result can be a system that feels frozen or responds very slowly.

Configured swap can help prevent abrupt memory-allocation failures by providing emergency headroom. It cannot solve a persistent RAM shortage. If frequent paging is performance-limiting, reduce memory demand, tune or stop the offending workload, or add RAM. A larger swap area alone normally makes the system slower for longer rather than restoring RAM-like speed.

Understanding a Swap Partition

A swap partition is a dedicated partition formatted with a Linux swap signature. It is not mounted as a normal directory tree, so it has no usable path such as /swap or /home. The kernel accesses it as a block device.

A system can have one or more active swap areas. They may be partitions, files, or a mixture of both. The kernel assigns each active area a swap priority, a value that influences which area it prefers.

An example disk layout might look like this:

/dev/nvme0n1p1   EFI or boot filesystem
/dev/nvme0n1p2   root filesystem  /
/dev/nvme0n1p3   home filesystem  /home
/dev/nvme0n1p4   swap partition   not mounted

The exact layout varies by installation. Do not assume that a device name or partition number is safe to use without checking it.

Inspecting Configured and Active Swap

Use swapon to inspect active swap areas. The output identifies the swap name or path, type, total size, used capacity, and priority.

swapon --show
swapon -s

swapon --show presents a clear column-based listing. swapon -s displays a summary and is retained for compatibility with the traditional command form.

Use free to compare physical memory and swap totals:

free -h

The output includes RAM totals, used and available memory, and swap totals and usage. “Available” memory is an estimate of memory that can be given to applications without severe reclaim activity; it is not simply the same as unused memory. Linux may use RAM for filesystem caches, and reclaimable cached memory can still contribute to available memory.

The kernel also exposes active swap information through /proc/swaps:

cat /proc/swaps

To relate an active swap device to the disk layout, use:

lsblk -f

Look for a block device whose filesystem type is swap, then compare it with the path shown by swapon --show.

CommandPurposeExample useImportant caution
swapon -sDisplay a summary of active swap areasswapon -sUse the listed devices as evidence; do not infer a target from memory
swapon --showDisplay active swap areas in columnsswapon --showShows active areas, not every possible unused partition
free -hShow human-readable RAM and swap totals and usagefree -hInterpret swap usage together with availability and system behavior
cat /proc/swapsRead the kernel's active swap listcat /proc/swapsDoes not list inactive swap areas
mkswapInitialize a partition or file with a swap signaturesudo mkswap /dev/DEVICEDestroys existing data or filesystem metadata on the target
swaponActivate initialized swapsudo swapon /dev/DEVICEVerify the device before activation
swapoffDeactivate active swapsudo swapoff /dev/DEVICERequires enough RAM to absorb pages currently in swap
blkidRetrieve UUID and type informationsudo blkid /dev/DEVICEUse the UUID from the intended partition
lsblk -fShow block devices, types, labels, and UUIDslsblk -fNever format a device merely because it appears in the list

Enabling and Disabling Swap

swapon activates an already initialized swap partition or swap file. Administrative changes generally require root privileges, commonly supplied with sudo.

To activate a known, correctly identified swap partition:

sudo swapon /dev/DEVICE
swapon --show
free -h

Replace /dev/DEVICE only after verifying that it is the intended swap partition. Activation normally lasts until reboot unless the area is also configured in /etc/fstab.

swapoff deactivates an active swap area:

sudo swapoff /dev/DEVICE

Before disabling swap, the kernel must move pages currently stored there back into RAM. The command may fail, or memory pressure may become dangerous, if available RAM is insufficient. Reduce memory usage before retrying.

Creating and Persisting a Swap Partition

Creating swap on a partition is a destructive operation. First select unused storage carefully and identify it with commands such as lsblk -f. Then initialize and activate it:

sudo mkswap /dev/DEVICE
sudo swapon /dev/DEVICE
swapon --show
free -h

mkswap writes the swap signature and metadata. It does not create a directory or normal filesystem. Running it against the wrong partition can destroy existing data or filesystem metadata.

To enable the partition automatically at boot, obtain its UUID:

sudo blkid /dev/DEVICE

Add an entry for the actual UUID to /etc/fstab:

UUID=partition-uuid none swap defaults 0 0

/etc/fstab is a system configuration file that defines storage resources to activate during boot. The none field reflects that swap is not mounted as a directory tree, and swap identifies the resource type.

Validate an edit before relying on the next reboot. Check the UUID against blkid, inspect the entry for spelling and field errors, and test fstab-defined swap with:

sudo swapon -a
swapon --show

Use UUID-based references for partitions because device names can change when hardware, enumeration order, or storage configuration changes. A faulty /etc/fstab entry can prevent swap from activating at boot, so keep the target and syntax under careful review.

Swap Sizing Guidance

A traditional guideline suggests allocating approximately one to two times installed RAM. Treat this as a historical starting point, not a universal rule. Modern systems need a plan based on actual requirements.

FactorWhy it mattersPlanning implication
Installed RAMMore RAM usually reduces ordinary paging, while smaller RAM capacity can increase pressureUse RAM size as one input, not the only sizing rule
Typical workloadDatabases, virtual machines, builds, browsers, and scientific workloads can have very different memory demandsMeasure peak usage and allow appropriate headroom
HibernationHibernation saves a memory image to nonvolatile storage before shutdownNormally provide swap capacity sufficient for the memory image, with implementation-specific overhead
Disk capacitySwap competes with filesystems and other storage needsBalance memory headroom against available disk space
Storage performancePaging to fast storage is less slow than paging to an HDD, but remains slower than RAMDo not use storage speed as a reason to treat swap as RAM
Need for emergency memory headroomTemporary allocation spikes may be safer when some swap is availableKeep some swap even on systems that rarely use it, when practical

Systems with abundant RAM may use little or no swap during ordinary workloads, but configured swap can still provide emergency headroom. Hibernation has stricter capacity requirements than ordinary swapping.

Monitoring Swap in Practice

Monitor swap together with RAM use, available memory, load, paging activity, storage I/O, and application behavior. Nonzero swap usage alone does not prove a problem.

free -h
swapon --show
vmstat 1

In vmstat output, recurring paging activity can help reveal active memory pressure. Inspect memory-heavy processes with:

top
ps

If paging remains high and the system is consistently slow, reduce the workload's memory consumption, stop or tune the offending process, redesign capacity, or add RAM.

Practical Examples

Inspect swap after installation

  1. Run swapon --show or swapon -s.
  2. Interpret the path, type, size, used amount, and priority.
  3. Compare the totals and current usage with free -h.

Identify a swap partition on a disk

  1. Run lsblk -f.
  2. Locate the entry whose type is swap.
  3. Confirm that it matches the active entry shown by swapon --show.

Activate an existing initialized partition

  1. Verify the target device and ensure it is the intended partition.
  2. Run sudo swapon /dev/DEVICE.
  3. Confirm activation with swapon --show and free -h.

Create and persist a new swap area

  1. Select unused storage carefully.
  2. Initialize it with sudo mkswap /dev/DEVICE.
  3. Enable it with sudo swapon /dev/DEVICE.
  4. Obtain its UUID with sudo blkid /dev/DEVICE.
  5. Add the correct UUID entry to /etc/fstab.
  6. Test the configuration with sudo swapon -a and verify the result.

Troubleshooting

swapon shows no active swap

  • Run lsblk -f to find a partition with type swap.
  • Check /etc/fstab for a missing or incorrect entry.
  • Use swapon --show and cat /proc/swaps to verify the active state.
  • Initialize and activate the correct area, then add a persistent entry if required.

The system is very slow and swap use is high

  • Check free -h and vmstat 1.
  • Inspect memory-consuming processes with top or ps.
  • Determine whether storage I/O rises while responsiveness falls.
  • Reduce memory demand, tune or stop the workload, or plan a RAM upgrade. A larger swap area alone will not restore RAM-like performance.

swapoff fails

  • Check available memory with free -h.
  • Stop or reduce memory-heavy applications.
  • Retry only when RAM can absorb the pages currently in swap.

Swap is not active after reboot

  • Compare the blkid output with the /etc/fstab UUID.
  • Check boot messages for storage or fstab errors.
  • Run swapon --show after boot.
  • Correct the persistent entry and test it with sudo swapon -a.

A partition cannot be activated as swap

  • Inspect its type and current use with lsblk -f.
  • Confirm that the intended unused target was initialized with mkswap.
  • Check whether another filesystem, volume manager, or encryption layer is using it.
  • Never format, initialize, activate, or disable a disk device until its identity and purpose are confirmed.

Exam-Relevant Notes

  • Swap is disk-backed virtual-memory storage, not equivalent to physical RAM.
  • Paging moves memory pages between RAM and swap.
  • Heavy, sustained paging can cause swap thrashing and severe slowdown.
  • A swap partition is not mounted as a normal directory tree.
  • swapon --show, free -h, and /proc/swaps show active or used swap information in different forms.
  • mkswap initializes an area; swapon activates it; swapoff deactivates it.
  • Manual activation is temporary unless an appropriate /etc/fstab entry is configured.
  • UUID references are generally more stable than device names in persistent configuration.
  • Swap sizing depends on workload, RAM, storage, disk capacity, emergency headroom, and hibernation requirements.

For a concise reference, see Linux swap partition and swapon reference.