Table of Contents
- What is Swap Space?
- Types of Swap Space
- Checking Existing Swap Space
- Creating a Swap Partition
- Creating a Swap File
- Enabling Swap Space
- Making Swap Space Persistent Across Reboots
- Adjusting Swappiness
- Disabling and Removing Swap Space
- Best Practices for Swap Space
- Troubleshooting Common Swap Issues
- Conclusion
- References
1. What is Swap Space?
Swap space is a reserved portion of your storage (HDD/SSD) that the Linux kernel uses as “virtual memory.” When your physical RAM is full, the kernel moves inactive data from RAM to swap space, freeing up RAM for active processes. This process is called paging (moving individual pages of data) or swapping (moving entire processes, though modern Linux uses paging more often).
Key Roles of Swap Space:
- Prevents OOM Errors: When RAM is exhausted, swap allows the system to continue running by offloading data to disk.
- Supports Hibernation: To hibernate, the system saves the contents of RAM to swap space, then powers off. On reboot, it restores from swap.
- Improves Multitasking: Enables running more applications simultaneously, even if they exceed physical RAM.
2. Types of Swap Space
Linux supports two primary types of swap space: swap partitions and swap files. Each has tradeoffs, and the choice depends on your use case.
Swap Partition
A dedicated disk partition formatted for swap.
- Pros: Slightly better performance (no filesystem overhead), ideal for hibernation, and easier to manage on static storage setups.
- Cons: Harder to resize later (requires repartitioning), not ideal for dynamic storage (e.g., cloud instances with limited disk partitions).
Swap File
A regular file on an existing filesystem, formatted for swap.
- Pros: Easy to create, resize, or delete without repartitioning. Ideal for systems with limited disk partitions (e.g., VMs, cloud servers).
- Cons: Slightly slower than a partition (due to filesystem overhead), may not work with hibernation on some systems (depends on the filesystem).
3. Checking Existing Swap Space
Before creating new swap space, check if your system already has swap configured. Use these commands:
1. swapon -s (Swap Summary)
Shows active swap devices/files, their type, size, and usage:
swapon -s
Example output:
Filename Type Size Used Priority
/swapfile file 4194300 0 -2
2. free -h (Human-Readable Memory Stats)
Displays total, used, and free RAM and swap:
free -h
Example output:
total used free shared buff/cache available
Mem: 15Gi 2.3Gi 10Gi 345Mi 3.1Gi 12Gi
Swap: 4.0Gi 0B 4.0Gi
3. top or htop (Interactive Process Monitor)
These tools show real-time swap usage in the “Swap” row (for top) or a dedicated swap meter (for htop).
4. /proc/meminfo (Raw Memory Data)
Check swap details in the kernel’s memory info file:
grep Swap /proc/meminfo
Example output:
SwapTotal: 4194300 kB
SwapFree: 4194300 kB
SwapCached: 0 kB
4. Creating a Swap Partition
A swap partition is a dedicated slice of your disk. Follow these steps to create one:
Prerequisites:
- A free disk partition (or unallocated space on a disk).
- Root access (use
sudo).
Step 1: Identify Disk and Free Space
Use lsblk to list disks and partitions. Look for unallocated space (marked as free):
lsblk
Example output (look for /dev/sda or /dev/nvme0n1):
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
sda 8:0 0 500G 0 disk
├─sda1 8:1 0 512M 0 part /boot/efi
├─sda2 8:2 0 20G 0 part /
└─sda3 8:3 0 279G 0 part /home
sdb 8:16 0 100G 0 disk # Unpartitioned disk (we’ll use this)
Step 2: Create a Swap Partition
Use a tool like fdisk (for MBR disks) or parted (for GPT disks) to create a partition. Here, we’ll use fdisk on /dev/sdb (adjust for your disk):
-
Launch
fdiskfor the target disk:sudo fdisk /dev/sdb -
Press
nto create a new partition. -
Choose
pfor primary (orefor extended, if needed). -
Accept the default partition number (e.g.,
1). -
Set the start sector (default: first available) and end sector (e.g.,
+4Gfor a 4GB swap partition). -
Press
tto set the partition type. For swap:- MBR disks: Enter
82(Linux swap). - GPT disks: Enter
0657FD6D-A4AB-43C4-84E5-0933C84B4F4F(GUID for swap).
- MBR disks: Enter
-
Press
wto write changes and exit.
Step 3: Format the Partition as Swap
Use mkswap to format the new partition (replace /dev/sdb1 with your partition):
sudo mkswap /dev/sdb1
Example output:
Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
no label, UUID=abc12345-6789-0def-ghij-klmnopqrstuv
Step 4: Enable the Swap Partition
Temporarily enable the swap partition with swapon:
sudo swapon /dev/sdb1
Step 5: Make Swap Persistent Across Reboots
To ensure the swap partition is enabled on boot, add it to /etc/fstab.
-
Get the partition’s UUID (from
mkswapoutput orblkid):sudo blkid /dev/sdb1Example output:
/dev/sdb1: UUID="abc12345-6789-0def-ghij-klmnopqrstuv" TYPE="swap" PARTUUID="xyz78901-2345-6abc-defg-hijklmnopqrs" -
Edit
/etc/fstabwith a text editor (e.g.,nano):sudo nano /etc/fstab -
Add this line (replace
UUID=...with your partition’s UUID):UUID=abc12345-6789-0def-ghij-klmnopqrstuv none swap defaults 0 0 -
Save and exit (
Ctrl+O,Enter,Ctrl+Xinnano). -
Test the
fstabentry to avoid boot issues:sudo mount -aIf no errors appear, the configuration is valid.
5. Creating a Swap File
If you prefer not to repartition your disk, a swap file is a flexible alternative.
Step 1: Create the Swap File
Use fallocate (fast) or dd (universal) to create a file.
Option 1: fallocate (Recommended for Most Systems)
fallocate instantly allocates space (no zeroing). Replace 4G with your desired size (e.g., 8G for 8GB):
sudo fallocate -l 4G /swapfile
Note: fallocate may fail on some filesystems (e.g., ZFS, XFS with certain options). If so, use dd (below).
Option 2: dd (Fallback)
dd creates the file by writing zeros (slower but reliable). For a 4GB file:
sudo dd if=/dev/zero of=/swapfile bs=1G count=4 status=progress
if=/dev/zero: Input file (source of zeros).of=/swapfile: Output file (the swap file).bs=1G: Block size (1GB per block).count=4: Number of blocks (4 blocks = 4GB).
Step 2: Secure the Swap File
Set strict permissions to prevent unauthorized access (only root should read/write):
sudo chmod 600 /swapfile
Step 3: Format the File as Swap
Use mkswap to initialize the file as swap:
sudo mkswap /swapfile
Example output:
Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
no label, UUID=def45678-9012-3abc-defg-hijklmnopqrst
Step 4: Enable the Swap File
Temporarily enable the swap file:
sudo swapon /swapfile
Step 5: Make Swap Persistent Across Reboots
Add the swap file to /etc/fstab (replace /swapfile with your file path):
-
Edit
/etc/fstab:sudo nano /etc/fstab -
Add this line:
/swapfile none swap defaults 0 0 -
Save, exit, and test with
sudo mount -a(no errors = success).
6. Enabling Swap Space
To enable swap manually (e.g., after creating a new swap file/partition), use swapon:
-
Enable a specific swap device/file:
sudo swapon /dev/sdb1 # For a partition sudo swapon /swapfile # For a file -
Enable all swap entries in
/etc/fstab:sudo swapon -a -
Enable with verbose output (to debug):
sudo swapon -v /swapfile
7. Making Swap Space Persistent
As shown earlier, editing /etc/fstab ensures swap is enabled on boot. Always verify the fstab entry with sudo mount -a to avoid breaking the system.
Critical Notes for /etc/fstab:
- Use
UUID=for partitions (more reliable than/dev/sdXpaths, which can change). - For swap files, use the full path (e.g.,
/swapfile). - The
defaultsoption is sufficient for swap (includesrw,async, andsw). - The last two fields (
0 0) mean “no dump” and “no filesystem check” (swap doesn’t need checks).
8. Adjusting Swappiness
Swappiness is a Linux kernel parameter (vm.swappiness) that controls how aggressively the system swaps data from RAM to disk. It ranges from 0 to 100:
0: Swap only when RAM is completely full (risk of OOM errors).100: Swap aggressively (frees RAM for cache, but slower due to disk I/O).
Default Swappiness:
- Desktop systems: Typically
60(balances performance and RAM usage). - Servers: Often lower (e.g.,
10-20) to prioritize RAM for critical processes.
How to Adjust Swappiness
1. Check Current Swappiness:
cat /proc/sys/vm/swappiness
2. Temporary Change (Until Reboot):
Use sysctl to set a new value (e.g., 10):
sudo sysctl vm.swappiness=10
3. Permanent Change (Survives Reboots):
Edit /etc/sysctl.conf (or create a file in /etc/sysctl.d/):
-
Open the config file:
sudo nano /etc/sysctl.conf -
Add this line (replace
10with your desired value):vm.swappiness=10 -
Save, exit, and apply changes:
sudo sysctl -p
9. Disabling and Removing Swap Space
Disabling Swap Temporarily
Use swapoff to disable a swap device/file:
sudo swapoff /dev/sdb1 # Disable a partition
sudo swapoff /swapfile # Disable a file
sudo swapoff -a # Disable all swap
Removing Swap Permanently
For a Swap Partition:
-
Disable the swap:
sudo swapoff /dev/sdb1 -
Remove the entry from
/etc/fstab. -
Delete the partition (use
fdiskorparted):sudo fdisk /dev/sdbPress
dto delete the partition, thenwto save changes.
For a Swap File:
-
Disable the swap:
sudo swapoff /swapfile -
Remove the entry from
/etc/fstab. -
Delete the swap file:
sudo rm /swapfile
10. Best Practices for Swap Space
Size Recommendations
- General Use: 1-2x RAM for systems with <2GB RAM; 1GB-equal to RAM for >2GB RAM.
- Hibernation: At least equal to RAM (to store the entire RAM contents).
- Servers: Start with 1GB swap, adjust based on workload (monitor with
free -h).
Performance Tips
- Use SSDs for Swap: SSDs are much faster than HDDs for swap, reducing I/O lag.
- Avoid Multiple Swap Devices: If using multiple swaps, set priorities with
swapon -p(higher priority = used first). - Monitor Swap I/O: Use
vmstat 1oriostatto check for excessive swapping (highsi/sovalues invmstatindicate performance issues).
Security
- Encrypt Swap (Optional): Use
cryptswapto encrypt swap space, preventing data leaks if the disk is stolen. Guides for encrypted swap are distribution-specific (e.g., Ubuntu’scrypttab).
11. Troubleshooting Common Swap Issues
Swap Not Mounting on Boot
- Check
/etc/fstabsyntax: Usesudo mount -ato test for errors. - Verify UUID/path: Ensure the UUID (for partitions) or path (for files) in
fstabis correct. - Check permissions: Swap files must have
chmod 600; partitions must be formatted withmkswap.
”swapon: Permission Denied”
- Ensure the swap file has
600permissions:sudo chmod 600 /swapfile. - Verify the file/partition exists and is formatted as swap.
Hibernation Fails
- Hibernation requires swap space ≥ RAM. Check with
free -h. - Some systems (e.g., UEFI with secure boot) may block hibernation. Disable secure boot or use
resume=UUID=...in the kernel boot parameters.
12. Conclusion
Swap space is a vital tool for Linux memory management, ensuring stability when RAM is full and enabling features like hibernation. Whether you choose a swap partition (for performance) or a swap file (for flexibility), the steps outlined here will help you set up, configure, and manage swap space effectively.
By following best practices—monitoring usage, adjusting swappiness, and securing swap—you can optimize your system’s performance and reliability.