Swap space extends your server's effective memory by using disk storage when RAM is exhausted. While not a substitute for more RAM, properly configured swap prevents out-of-memory (OOM) kills on production Linux servers.
What Is Swap?
When RAM is full, the Linux kernel moves inactive memory pages from RAM to swap space on disk. This process is called swapping.
- Page-out (swap-in): Data moves from RAM → swap (when RAM is full)
- Page-in (swap-out): Data moves from swap → RAM (when RAM frees up)
- Virtual memory = Physical RAM + Swap space
Swap Sizing Rules
| RAM Size | Recommended Swap |
|---|---|
| ≤ 2 GB | 2 × RAM |
| > 2 GB | RAM + 2 GB |
| 4–16 GB | Minimum 4 GB |
| 16–64 GB | Minimum 8 GB |
| 64–256 GB | Minimum 16 GB |
Creating a Swap Partition
# Step 1 — Create partition with type 82 (Linux Swap):
# fdisk /dev/sdb
Command: n → p → [Enter] → +2048M
Command: t → 82 # Linux Swap hex code
Command: w
# partprobe /dev/sdb
# Step 2 — Format as swap:
# mkswap /dev/sdb2
# Step 3 — Enable:
# swapon /dev/sdb2
# free -m # verify new swap size
# Step 4 — Make permanent (/etc/fstab):
# vim /etc/fstab
/dev/sdb2 swap swap defaults 0 0
# mount -a
Creating a Swap File (No Partition Needed)
Use this when you can't create a new partition (disk full or partition limit reached).
# Create 2 GB empty file:
# dd if=/dev/zero of=/root/linuxswap bs=1M count=2048
# Convert to swap:
# mkswap /root/linuxswap
# Enable:
# swapon /root/linuxswap
# free -m
# Make permanent:
# vim /etc/fstab
/root/linuxswap swap swap defaults 0 0
# mount -a
Removing Swap
# Disable swap:
# swapon -s # list active swap
# swapoff /dev/sdb2 # disable
# vim /etc/fstab # remove entry
# fdisk /dev/sdb → d → w # delete partition
# partprobe /dev/sdb
Monitoring Memory
# free -m # RAM and swap in MB
# free -h # human readable
# cat /proc/meminfo # detailed memory breakdown
# vmstat 1 5 # memory + swap activity every 1 sec
# vmstat -s # memory statistics summary
# sar -r 1 5 # memory utilization report
Troubleshooting Memory Issues
# What happens when /usr is full?
# → Users cannot login; logged-in users can't run commands
# What happens when swap/page space is full?
# → New applications can't load
# → Users can't access application features
# → Solution: increase swap, or kill memory-hungry processes
# Find top memory consumers:
# ps aux --sort=-%mem | head -10
# top (press M to sort by memory)
# Check for OOM kills:
# dmesg | grep -i "oom\|killed"
# grep -i oom /var/log/messages