Sagar.BlogArticle
All posts
All posts
Linux

Swap Space — Virtual Memory on Linux

Understand how Linux swap space extends RAM, how to create and manage swap files, and how to tune swappiness for your workload.

March 24, 20255 min read
linuxdiskswapmemoryperformance

What is Swap?

When physical RAM fills up, the Linux kernel moves inactive memory pages to swap space on disk. This prevents out-of-memory crashes at the cost of speed — disk is much slower than RAM.

Check Swap Status

swapon --show              # Active swap areas
free -h                    # Memory + swap overview
cat /proc/swaps            # Swap device details

Create a Swap File

# Create a 2GB swap file
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile       # Secure permissions
sudo mkswap /swapfile          # Initialize as swap
sudo swapon /swapfile          # Activate it

# Make permanent — add to /etc/fstab
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Manage Swap

# Disable swap
sudo swapoff /swapfile

# Resize (disable → fallocate → format → enable)
sudo swapoff /swapfile
sudo fallocate -l 4G /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Swappiness — Tuning Swap Behavior

Swappiness (0–100) controls how aggressively the kernel uses swap. Lower = prefer RAM.

# Check current swappiness (default: 60)
cat /proc/sys/vm/swappiness

# Temporary change (until reboot)
sudo sysctl vm.swappiness=10

# Permanent change
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
ValueBehavior
0Avoid swap completely
10–30Light swap (good for desktops with SSD)
60Default
100Aggressive swapping

Set swappiness to 10 on systems with SSDs to reduce unnecessary wear and improve responsiveness. Keep it at 60 for servers.

Quick Check

What happens when swappiness is set to 0?

Exercise

Check your current swap usage with free -h. Then check the swappiness value and print it.