sqlite
+
css
+
htmx
elm
argocd
0x
+
+
+
node
bundler
+
play
+
tls
+
+
+
yaml
numpy
+
+
+
mint
circle
+
surrealdb
+
+
yaml
+
+
+
gradle
+
vb
eclipse
+
ฮป
jwt
+
java
f#
grpc
+
quarkus
+
mongo
sublime
java
+
+
+
istio
laravel
โˆซ
preact
couchdb
marko
matplotlib
solid
+
vb
+
yarn
sublime
rest
groovy
+
+
+
+
+
+
vault
+
zig
+
centos
influxdb
+
+
mint
โˆž
webpack
+
cobol
Back to Blog
๐Ÿ’พ Swap Memory Management and Configuration in AlmaLinux: Complete Guide
AlmaLinux Swap Memory Memory Management

๐Ÿ’พ Swap Memory Management and Configuration in AlmaLinux: Complete Guide

Published Aug 20, 2025

Learn to configure and manage swap memory in AlmaLinux. Create swap files, partitions, and optimize swap settings with easy-to-follow examples for beginners.

10 min read
0 views
Table of Contents

๐Ÿ’พ Swap Memory Management and Configuration in AlmaLinux: Complete Guide

Running out of RAM and your systemโ€™s crawling? Programs crashing randomly? ๐Ÿ˜ฐ Thatโ€™s where swap memory comes to the rescue! Think of swap as emergency RAM on your hard drive. I remember when I first learned about swapโ€ฆ My server kept crashing until I configured it properly. Now? Smooth sailing! Today Iโ€™ll show you everything about swap memory - how to create it, manage it, and make your system bulletproof. Letโ€™s dive in! ๐ŸŠโ€โ™‚๏ธ

๐Ÿค” Why is Swap Memory Important?

So hereโ€™s the thing - even if you have tons of RAM, swap is still super important! Let me explain why:

  • ๐Ÿ›ก๏ธ Safety Net - Prevents crashes when RAM fills up
  • ๐Ÿ’ค Hibernation - Stores memory contents during sleep
  • ๐Ÿ“Š Better Memory Usage - Moves inactive data to disk
  • ๐Ÿš€ Handles Spikes - Survives temporary memory surges
  • ๐Ÿ’ฐ Cost Effective - Cheaper than buying more RAM
  • ๐Ÿ”ง System Stability - Prevents OOM (Out of Memory) killer

Trust me, that one time my database server ran without swap? It crashed during a backup and corrupted data. Never again! ๐Ÿ˜…

๐ŸŽฏ What You Need

Before we start managing swap, check you have:

  • โœ… AlmaLinux system running
  • โœ… Root or sudo access
  • โœ… Some free disk space (at least 1GB)
  • โœ… 15 minutes to bulletproof your system
  • โœ… Basic terminal knowledge

๐Ÿ“ Step 1: Understanding Current Swap Status

First, letโ€™s see what swap you already have (if any)!

Check Current Swap

# See swap summary
free -h

# Output looks like:
#               total        used        free      shared  buff/cache   available
# Mem:           7.7G        2.1G        3.9G        145M        1.7G        5.2G
# Swap:          2.0G        0.0G        2.0G

# Detailed swap info
swapon --show

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

# Another way to check
cat /proc/swaps

# Check swap usage percentage
free | grep Swap | awk '{print ($3/$2)*100 "%"}'

Understanding Swappiness

# Check current swappiness (0-100)
cat /proc/sys/vm/swappiness

# Default is usually 60
# Lower = less swap usage
# Higher = more aggressive swapping

# Check other swap settings
sysctl vm.swappiness
sysctl vm.vfs_cache_pressure
sysctl vm.dirty_ratio

What these numbers mean: ๐Ÿ“Š

  • swappiness=0 = Only swap to prevent OOM
  • swappiness=10 = Minimal swap (good for SSDs)
  • swappiness=60 = Default balanced approach
  • swappiness=100 = Aggressive swapping

๐Ÿ”ง Step 2: Creating Swap Space

No swap? Letโ€™s create some! You can use a file or partition.

Method 1: Create Swap File (Easier!)

# Create 2GB swap file
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

# Or use fallocate (faster!)
sudo fallocate -l 2G /swapfile

# Set correct permissions (IMPORTANT!)
sudo chmod 600 /swapfile

# Verify permissions
ls -lh /swapfile
# Should show: -rw------- 1 root root 2.0G

# Make it swap space
sudo mkswap /swapfile

# Output:
# Setting up swapspace version 1, size = 2 GiB
# no label, UUID=12345678-1234-1234-1234-123456789abc

# Enable swap
sudo swapon /swapfile

# Verify it's working
swapon --show
free -h

Method 2: Create Swap Partition

# List disks
lsblk

# Create partition with fdisk
sudo fdisk /dev/sdb

# In fdisk:
# n - new partition
# p - primary
# 1 - partition number
# Enter - default first sector
# +2G - size
# t - change type
# 82 - Linux swap
# w - write changes

# Format as swap
sudo mkswap /dev/sdb1

# Enable swap partition
sudo swapon /dev/sdb1

# Check
swapon --show

Make Swap Permanent

# Backup fstab first (ALWAYS!)
sudo cp /etc/fstab /etc/fstab.backup

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

# Or for swap partition
echo '/dev/sdb1 none swap sw 0 0' | sudo tee -a /etc/fstab

# Test fstab (IMPORTANT!)
sudo mount -a

# If no errors, you're good!

๐ŸŒŸ Step 3: Optimizing Swap Performance

Letโ€™s make swap work efficiently! ๐Ÿš€

Adjust Swappiness

# Check current value
cat /proc/sys/vm/swappiness

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

# Make permanent
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

# For desktop systems (lots of RAM)
sudo sysctl vm.swappiness=10

# For servers
sudo sysctl vm.swappiness=30

# For low RAM systems
sudo sysctl vm.swappiness=60

# Apply changes
sudo sysctl -p

Multiple Swap Spaces

# Create additional swap
sudo fallocate -l 1G /swapfile2
sudo chmod 600 /swapfile2
sudo mkswap /swapfile2
sudo swapon /swapfile2

# Set priorities (higher = used first)
sudo swapon -p 10 /swapfile
sudo swapon -p 5 /swapfile2

# Check priorities
swapon --show

# Add to fstab with priority
echo '/swapfile none swap sw,pri=10 0 0' | sudo tee -a /etc/fstab
echo '/swapfile2 none swap sw,pri=5 0 0' | sudo tee -a /etc/fstab

Cache Pressure Settings

# Adjust cache pressure (default 100)
sudo sysctl vm.vfs_cache_pressure=50

# Lower = keep cache longer
# Higher = reclaim cache aggressively

# Make permanent
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf

# Dirty ratio (when to write to disk)
sudo sysctl vm.dirty_ratio=15
sudo sysctl vm.dirty_background_ratio=5

โœ… Step 4: Managing and Monitoring Swap

Keep an eye on your swap usage! ๐Ÿ‘€

Monitor Swap Usage

# Real-time monitoring
watch -n 1 free -h

# Swap usage by process
for file in /proc/*/status; do 
    awk '/VmSwap|Name/{printf $2 " " $3}END{print ""}' $file 2>/dev/null
done | sort -k 2 -n -r | head -10

# Or use smem (install first)
sudo dnf install -y smem
smem -s swap -r | head -10

# Check swap I/O
vmstat 1

# Look at si (swap in) and so (swap out)

Clear Swap (If Needed)

# Only do this if you have enough free RAM!

# Check if safe
free -h

# If Mem free > Swap used, then:
sudo swapoff -a
sudo swapon -a

# This moves everything back to RAM

๐ŸŽฎ Quick Examples

Example 1: Auto-Resize Swap Script ๐Ÿ”„

#!/bin/bash
# Dynamic swap management

# Check memory pressure
check_memory() {
    local mem_percent=$(free | grep Mem | awk '{print ($3/$2)*100}')
    local swap_percent=$(free | grep Swap | awk '{if($2>0) print ($3/$2)*100; else print 0}')
    
    echo "Memory used: ${mem_percent%.*}%"
    echo "Swap used: ${swap_percent%.*}%"
    
    # If memory >90% and swap exists
    if (( $(echo "$mem_percent > 90" | bc -l) )); then
        echo "โš ๏ธ High memory usage detected!"
        
        # Check if we need more swap
        if [ ! -f /swapfile_emergency ]; then
            echo "Creating emergency swap..."
            sudo fallocate -l 1G /swapfile_emergency
            sudo chmod 600 /swapfile_emergency
            sudo mkswap /swapfile_emergency
            sudo swapon /swapfile_emergency
            echo "โœ… Emergency swap activated!"
        fi
    fi
}

# Run check
check_memory

Example 2: Swap Health Monitor ๐Ÿ“Š

#!/bin/bash
# Monitor swap health and alert

THRESHOLD=80  # Alert if swap usage > 80%

# Create monitoring function
monitor_swap() {
    while true; do
        # Get swap usage percentage
        if [ -f /proc/swaps ]; then
            swap_total=$(free | grep Swap | awk '{print $2}')
            swap_used=$(free | grep Swap | awk '{print $3}')
            
            if [ $swap_total -gt 0 ]; then
                swap_percent=$((swap_used * 100 / swap_total))
                
                echo "[$(date '+%H:%M:%S')] Swap usage: $swap_percent%"
                
                if [ $swap_percent -gt $THRESHOLD ]; then
                    echo "๐Ÿšจ ALERT: Swap usage critical!"
                    
                    # Find top swap users
                    echo "Top processes using swap:"
                    for proc in /proc/*/status; do
                        if [ -r "$proc" ]; then
                            awk '/Name|VmSwap/{printf $2" "}END{print""}' "$proc" 2>/dev/null
                        fi
                    done | sort -k2 -rn | head -5
                fi
            fi
        fi
        
        sleep 30
    done
}

# Run monitor
monitor_swap

Example 3: Optimal Swap Setup ๐ŸŽฏ

#!/bin/bash
# Configure optimal swap for system

echo "๐Ÿ”ง Configuring optimal swap settings..."

# Get total RAM
total_ram=$(free -b | awk '/^Mem:/{print $2}')
total_ram_gb=$((total_ram / 1024 / 1024 / 1024))

echo "System RAM: ${total_ram_gb}GB"

# Calculate recommended swap
if [ $total_ram_gb -le 2 ]; then
    swap_size=$((total_ram_gb * 2))
elif [ $total_ram_gb -le 8 ]; then
    swap_size=$total_ram_gb
else
    swap_size=8
fi

echo "Recommended swap: ${swap_size}GB"

# Create swap if doesn't exist
if [ ! -f /swapfile ]; then
    echo "Creating ${swap_size}GB swap file..."
    sudo fallocate -l ${swap_size}G /swapfile
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
    
    # Add to fstab
    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
fi

# Optimize settings based on system type
echo "Optimizing swap settings..."

# Check if SSD
if [ -f /sys/block/sda/queue/rotational ]; then
    rotational=$(cat /sys/block/sda/queue/rotational)
    if [ "$rotational" = "0" ]; then
        echo "SSD detected - using low swappiness"
        sudo sysctl vm.swappiness=10
    else
        echo "HDD detected - using moderate swappiness"
        sudo sysctl vm.swappiness=40
    fi
fi

# Make permanent
sudo sysctl -p

echo "โœ… Swap configuration complete!"

๐Ÿšจ Fix Common Problems

Problem 1: System Still Slow with Swap โŒ

Swap isnโ€™t magic - itโ€™s slower than RAM!

# Check if swap thrashing
vmstat 1 10
# Look for high si/so values

# Reduce swappiness
sudo sysctl vm.swappiness=1

# Find memory hogs
ps aux --sort=-%mem | head -10

# Consider adding RAM or optimizing apps

Problem 2: Canโ€™t Create Swap File โŒ

Getting errors creating swap?

# Check disk space
df -h /

# For "holes not supported" error, use dd instead
sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152

# For permission denied
sudo rm /swapfile  # If exists
sudo touch /swapfile
sudo chmod 600 /swapfile

Problem 3: Swap Not Activating on Boot โŒ

Swap disappears after reboot?

# Check fstab syntax
cat /etc/fstab | grep swap

# Should be exactly:
# /swapfile none swap sw 0 0

# Test without rebooting
sudo swapoff -a
sudo swapon -a

# Check for errors
sudo systemctl status swap.target

Problem 4: High Swap Usage โŒ

Swap constantly full?

# Find swap users
for proc in /proc/*/status; do
    awk '/Name|VmSwap/{printf $2" "}END{print""}' "$proc" 2>/dev/null
done | grep -v " 0 kB" | sort -k2 -rn

# Clear swap (if RAM available)
sudo swapoff -a && sudo swapon -a

# Increase swap size
sudo swapoff /swapfile
sudo rm /swapfile
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

๐Ÿ“‹ Simple Commands Summary

TaskCommand
๐Ÿ“Š Check swapfree -h or swapon --show
โž• Create swap filesudo fallocate -l 2G /swapfile
โœ… Enable swapsudo swapon /swapfile
โŒ Disable swapsudo swapoff /swapfile
๐Ÿ”ง Set swappinesssudo sysctl vm.swappiness=10
๐Ÿ’พ Make permanentAdd to /etc/fstab
๐Ÿ“ˆ Monitor swapvmstat 1
๐Ÿงน Clear swapsudo swapoff -a && sudo swapon -a

๐Ÿ’ก Tips for Success

  1. Size Matters ๐Ÿ“ - RAM โ‰ค2GB: 2ร—RAM, RAM >2GB: Equal to RAM
  2. SSD Friendly ๐Ÿ’ฟ - Use swappiness=10 for SSDs
  3. Monitor Usage ๐Ÿ‘€ - High swap = need more RAM
  4. Test Changes ๐Ÿงช - Always test fstab before reboot
  5. Multiple Swaps ๐ŸŽฏ - Use priorities for performance
  6. Regular Checks ๐Ÿ“… - Monitor swap health weekly

And hereโ€™s a pro tip: If your swap is constantly full, donโ€™t just add more swap - figure out WHY youโ€™re running out of RAM! Sometimes a memory leak is the real problem. ๐Ÿ”

๐Ÿ† What You Learned

Youโ€™re now a swap memory expert! You can:

  • โœ… Check and monitor swap usage
  • โœ… Create swap files and partitions
  • โœ… Configure swap for optimal performance
  • โœ… Tune swappiness for your needs
  • โœ… Troubleshoot swap issues
  • โœ… Set up automated swap management
  • โœ… Prevent OOM crashes

๐ŸŽฏ Why This Matters

Proper swap configuration means:

  • ๐Ÿ›ก๏ธ System never crashes from OOM
  • ๐Ÿš€ Better performance under load
  • ๐Ÿ’ฐ Postpone RAM upgrades
  • ๐Ÿ’ค Hibernation works properly
  • ๐Ÿ“Š Efficient memory management
  • ๐Ÿ”ง Professional system administration

Last week, our web server started getting more traffic than usual. Without swap? It wouldโ€™ve crashed hard. But with properly configured swap, it handled the spike perfectly until we could add more RAM. The boss was impressed that we had zero downtime! And now you can do the same! ๐Ÿ’ช

Remember: Swap is your safety net, not a RAM replacement. Configure it properly and your system will thank you by never crashing when things get tight! ๐ŸŒŸ

Happy swapping! May your memory never overflow and your system always stay responsive! ๐Ÿ’พโœจ