How to Configure Linux Swap Space for Better Performance
This guide explains what swap space is, why it’s essential for Linux systems, and provides step‑by‑step instructions for configuring swap files or partitions, viewing usage, and understanding its benefits for memory extension, performance optimization, and system stability.
Overview
Swap space is a disk‑based extension of RAM. When physical memory runs low, the kernel moves inactive pages to swap, freeing RAM for active processes. Although slower than RAM, swap prevents crashes caused by memory exhaustion.
Configuration Principles
The total swap size is usually recommended to be the larger of twice the physical RAM or 32 MB, but not exceeding 2 GB (adjust based on actual needs).
A dedicated swap partition is preferred for better performance and easier management.
Configuration Method (Linux)
Swap File
Disable any existing swap.
Create a swap file with
dd. Example for a 10 GB file:
sudo dd if=/dev/zero of=/swapfile bs=1G count=10Set permissions so only root can read/write:
sudo chmod 600 /swapfileMark the file as swap space:
sudo mkswap /swapfileActivate the swap file:
sudo swapon /swapfileSwap Partition
Use
fdiskor
partedto create a dedicated partition.
Format the partition as swap:
sudo mkswap /dev/sdXnActivate the partition:
sudo swapon /dev/sdXnViewing Swap Usage
free -m– shows memory and swap usage in megabytes.
free -m swapon --show– lists active swap files/partitions.
swapon --show cat /proc/swaps– displays detailed swap information.
cat /proc/swapsInteractive tools like
topor
htopalso display swap usage.
Benefits of Swap
Memory Extension : Provides additional virtual memory when RAM is insufficient.
Performance Optimization : Frees RAM for active processes by moving idle pages to disk.
System Stability : Prevents crashes or severe slowdowns caused by out‑of‑memory conditions.
Example: Creating an 8 GB Swap File
sudo dd if=/dev/zero of=/swapfile bs=1G count=8 # create 8 GB file
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfileVerify the configuration with:
free -mThe output should show the newly added swap space, confirming that the system is now equipped with additional virtual memory.
Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.