Docs / Linux Basics / How to Create and Manage Linux Swap Partitions

How to Create and Manage Linux Swap Partitions

By Admin · Mar 15, 2026 · Updated Apr 23, 2026 · 205 views · 2 min read

Swap space acts as an overflow area for RAM. When your server runs low on physical memory, the kernel moves less-used memory pages to swap, freeing RAM for active processes. While NVMe storage makes swap faster than ever, it is still orders of magnitude slower than RAM.

Check Current Swap Configuration

# View current swap usage
free -h
swapon --show

# Example output:
# NAME      TYPE SIZE USED PRIO
# /swapfile file  2G   0B   -2

Create a Swap File

# Create a 2GB swap file
sudo fallocate -l 2G /swapfile

# If fallocate is not available (some filesystems):
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

# Set correct permissions (CRITICAL for security)
sudo chmod 600 /swapfile

# Format as swap
sudo mkswap /swapfile

# Enable the swap file
sudo swapon /swapfile

# Verify
swapon --show
free -h

Make Swap Permanent

# Add to /etc/fstab so it persists after reboot
echo "/swapfile none swap sw 0 0" | sudo tee -a /etc/fstab

# Verify fstab syntax (a typo here can prevent booting)
sudo findmnt --verify

How Much Swap Do You Need?

# General recommendations for servers:
# RAM       Swap
# 1GB       2GB
# 2GB       2GB
# 4GB       2GB
# 8GB       2-4GB
# 16GB+     2-4GB (diminishing returns beyond this)

# The old 2x RAM rule is outdated for servers with 8GB+ RAM

Tuning Swap Behavior

# vm.swappiness controls how aggressively Linux uses swap
# Range: 0-100, Default: 60
# Server recommendation: 10

cat /proc/sys/vm/swappiness

# Change temporarily
sudo sysctl vm.swappiness=10

# Change permanently
echo "vm.swappiness=10" | sudo tee /etc/sysctl.d/99-swap.conf
sudo sysctl -p /etc/sysctl.d/99-swap.conf

Resize Swap

# Increase swap from 2GB to 4GB
sudo swapoff /swapfile
sudo fallocate -l 4G /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
free -h

Remove Swap

# Disable swap
sudo swapoff /swapfile
sudo sed -i "/swapfile/d" /etc/fstab
sudo rm /swapfile

Monitoring Swap Usage

# Watch swap usage over time
vmstat 5
# Look at the si (swap in) and so (swap out) columns
# If si/so are consistently greater than 0, you need more RAM

# Which processes are using swap?
sudo smem -s swap -r | head -10

Swap is a safety net, not a substitute for adequate RAM. If your server regularly uses swap, it is more cost-effective to upgrade RAM than to tolerate the performance penalty.

Was this article helpful?