Carlos Sura

Create and Tune a Linux Swap File on CentOS, RHEL & Rocky Linux

Small cloud instances (such as AWS EC2 t2.micro or t3.micro nodes with 1 GB of RAM) commonly ship without a swap partition enabled. When memory spikes during package builds, database queries, or cron jobs, the Linux Out-Of-Memory (OOM) killer abruptly terminates critical daemons like MySQL, Nginx, or Docker containers.

Adding a dedicated swap file provides a safety buffer against sudden memory exhaustion and allows the kernel to page out idle anonymous memory.


Allocate and Enable the Swap File

Run the following commands as root (or with sudo) to allocate a 2 GB swap file, lock down permissions to 0600 (so unprivileged local users cannot read swapped memory pages), format it as swap, and activate it immediately:

# Allocate a 2GB file (note: on older XFS filesystems on RHEL/CentOS 7, use dd if fallocate creates holes)
sudo fallocate -l 2G /swapfile

# If running on an older XFS filesystem where swapon reports "swapon failed: Invalid argument", use dd instead:
# sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

# Restrict read/write permissions strictly to root
sudo chmod 600 /swapfile

# Format the file as Linux swap space and enable it
sudo mkswap /swapfile
sudo swapon /swapfile

Persist the Swap File Across Reboots in /etc/fstab

Append the swap entry to /etc/fstab so the operating system mounts /swapfile automatically at boot:

/swapfile swap swap defaults 0 0

You can append this idempotently from the CLI with:

grep -q '^/swapfile ' /etc/fstab || echo '/swapfile swap swap defaults 0 0' | sudo tee -a /etc/fstab

Tune vm.swappiness and vm.vfs_cache_pressure

By default, many Linux distributions set vm.swappiness = 60, which causes the kernel to swap out process memory aggressively even when plenty of free RAM remains. On cloud servers backed by EBS/NVMe storage, lowering vm.swappiness to 10 instructs the kernel to keep active application memory in RAM and only swap under genuine memory pressure:

cat << 'EOF' | sudo tee /etc/sysctl.d/99-swap-tuning.conf
vm.swappiness = 10
vm.vfs_cache_pressure = 50
EOF

sudo sysctl --system

Verify Swap Status

Confirm that the swap file is active and inspect memory utilization:

sudo swapon --show
free -h