devops2025-06-20·7·18/348

Adding Swap Space on Linux: Complete Guide

How to add swap space on Linux using swap files and swap partitions, including swapon configuration and performance considerations.

Adding Swap Space on Linux: Complete Guide

When your Linux server runs out of physical RAM, it needs swap space to avoid out-of-memory kills. My trading analytics server hit memory limits during market open, and adding swap was the quick fix while I optimized the application. This guide covers both swap files and swap partitions.

Environment

  • OS: Ubuntu 22.04 LTS
  • RAM: 4GB
  • Current swap: 0B (none configured)
  • Goal: Add 8GB swap file
$ free -h
              total        used        free      shared  buff/cache   available
Mem:           3.8Gi       3.2Gi       100Mi       256Mi       500Mi       300Mi
Swap:            0B          0B          0B

The Problem

The OOM killer was terminating processes:

$ sudo dmesg | grep -i "oom\|out of memory"
[12345.678] Out of memory: Killed process 12345 (python3) total-vm:2048000kB, anon-rss:1800000kB
[12350.123] Out of memory: Killed process 6789 (node) total-vm:1024000kB, anon-rss:900000kB

# Check OOM score
$ cat /proc/12345/oom_score
# Process already killed, check last kill
$ sudo journalctl -k | grep "Killed process" | tail -5
Jun 20 14:30:00 server kernel: Killed process 12345 (python3) total-vm:2048000kB
Jun 20 14:30:05 server kernel: Killed process 6789 (node) total-vm:1024000kB

Analysis

Step 1: Check Current Swap Status

# Check if any swap exists
$ swapon --show
# No output = no swap

$ cat /proc/swaps
# No output

# Check fstab for swap entries
$ grep swap /etc/fstab
# No swap entry

Step 2: Check Available Disk Space

$ df -h /
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1       50G   32G   18G  64% /

# We have 18GB free - more than enough for 8GB swap

Solution

Option A: Create Swap File (Recommended)

# Create the swap file (8GB)
$ sudo fallocate -l 8G /swapfile

# If fallocate doesn't work (some filesystems), use dd
$ sudo dd if=/dev/zero of=/swapfile bs=1M count=8192 status=progress

# Set correct permissions (CRITICAL - must be 600)
$ sudo chmod 600 /swapfile

# Format as swap
$ sudo mkswap /swapfile
Setting up swapspace version 1, size = 8 GiB (8589930496 bytes)
no label, UUID=xxxx-xxxx-xxxx

# Enable the swap file
$ sudo swapon /swapfile

# Verify
$ swapon --show
NAME      TYPE SIZE USED PRIO
/swapfile file   8G   0B   -2

$ free -h
              total        used        free      shared  buff/cache   available
Mem:           3.8Gi       3.2Gi       100Mi       256Mi       500Mi       300Mi
Swap:         8.0Gi          0B       8.0Gi

Option B: Create Swap Partition

# If you have unallocated disk space
# Create partition (interactive)
$ sudo fdisk /dev/sdb

# Commands:
# n (new partition)
# p (primary)
# 3 (partition number)
# (default first sector)
# +8G (size)
# t (change type)
# 82 (Linux swap)
# w (write)

# Format as swap
$ sudo mkswap /dev/sdb3

# Enable
$ sudo swapon /dev/sdb3

# Get UUID
$ sudo blkid /dev/sdb3
/dev/sdb3: UUID="yyyy-yyyy-yyyy" TYPE="swap"

Make Swap Persistent (fstab)

# For swap file
$ echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# For swap partition
$ echo 'UUID=yyyy-yyyy-yyyy none swap sw 0 0' | sudo tee -a /etc/fstab

# Verify fstab
$ grep swap /etc/fstab
/swapfile none swap sw 0 0

Tune Swap Behavior

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

# For servers with enough RAM, lower swappiness
$ sudo sysctl -w vm.swappiness=10

# Make persistent
$ echo "vm.swappiness = 10" | sudo tee -a /etc/sysctl.conf

# Adjust vfs_cache_pressure (default 100)
$ sudo sysctl -w vm.vfs_cache_pressure=50
$ echo "vm.vfs_cache_pressure = 50" | sudo tee -a /etc/sysctl.conf

Verify Setup

# Check swap is active
$ swapon --show
NAME      TYPE  SIZE   USED PRIO
/swapfile file    8G 512MiB   -2

# Check memory status
$ free -h
              total        used        free      shared  buff/cache   available
Mem:           3.8Gi       3.0Gi       200Mi       256Mi       600Mi       500Mi
Swap:         8.0Gi       512Mi       7.5Gi

# Test swap usage
$ stress-ng --vm 2 --vm-bytes 4G --timeout 30s
# Monitor swap usage during test
$ watch -n 1 'free -h'

Troubleshooting

fallocate Not Supported

# Some filesystems (ext3, Btrfs) don't support fallocate for swap
$ sudo fallocate -l 8G /swapfile
fallocate: fallocate failed: Operation not supported

# Use dd instead
$ sudo dd if=/dev/zero of=/swapfile bs=1M count=8192

Permission Denied on Swapon

$ sudo swapon /swapfile
swapon: /swapfile: swapon failed: Operation not permitted

# Check permissions
$ ls -la /swapfile
-rw------- 1 root root 8589930496 Jun 20 10:00 /swapfile

# Ensure it's not a symlink
$ file /swapfile
/swapfile: Linux rev 1.0 ext4 filesystem data

# If on Btrfs, swap files need special handling
$ sudo btrfs filesystem mkswapfile --size 8G /swapfile
$ sudo swapon /swapfile

Recommended Swap Sizes

RAM SizeRecommended SwapNotes
2GB or less2x RAMMinimum for desktops
2-8GBEqual to RAMGood for servers
8-64GB8GB minimumEnough for most workloads
64GB+8-16GBHibernation needs more

Lessons Learned

  1. Swap permissions must be 600 - chmod 600 /swapfile is critical for security.
  2. Lower swappiness for servers - vm.swappiness=10 keeps processes in RAM longer.
  3. Swap is a safety net, not a solution - if you consistently use swap, add more RAM.
  4. Use swapon --show to verify swap is active after configuration.
  5. Monitor swap usage - high swap usage indicates memory pressure.

This blog does not accept any external sponsorships, affiliate marketing, or ad revenue.