html
+
+
+
istio
docker
java
+
prettier
+
+
+
+
hapi
argocd
+
gentoo
rb
toml
+
+
alpine
macos
+
+
numpy
+
rs
marko
istio
+
!!
+
+
eclipse
+
sklearn
+
bundler
^
scheme
next
+
zig
+
+
+
intellij
+
+
+
influxdb
js
mint
+
+
+
+
=>
phoenix
gentoo
pytest
tf
+
weaviate
django
swc
+
dns
+
+
+
+
+
+
+
react
sails
+
+
c++
pinecone
toml
+
dns
windows
+
abap
ts
Back to Blog
How to add swap space on Ubuntu 20.04
Linux Ubuntu

How to add swap space on Ubuntu 20.04

Published Nov 16, 2023

This tutorial explains how to add swap space on Ubuntu

4 min read
0 views
Table of Contents

When physical memory (RAM) is exhausted, Linux uses swap space as virtual memory. This tutorial explains how to add swap space on Ubuntu, helping your system handle memory-intensive applications and preventing out-of-memory errors.

Understanding Swap Space

Swap space serves as an overflow area for your RAM. When system memory is full, inactive pages are moved to swap, freeing up RAM for active processes. While swap is slower than RAM, it prevents system crashes and application failures.

When You Need Swap Space

  • Systems with limited RAM (< 8GB)
  • Memory-intensive applications (databases, compilation)
  • Hibernation support (swap ≥ RAM size)
  • Preventing OOM (Out of Memory) kills
  • Virtual machines and containers

Prerequisites

Before creating swap space, ensure you have:

  • Administrative (sudo) access
  • Sufficient disk space
  • Ubuntu 16.04 or later (instructions work for 18.04, 20.04, 22.04)

Checking Current System Status

Check Existing Swap

First, verify if swap is already configured:

sudo swapon --show

If no output, no swap is active. You can also check with:

cat /proc/swaps
free -h

Check Available Disk Space

Ensure sufficient space for swap file:

df -h /

Swap Space Calculation Guidelines

Choose swap size based on your system needs:

RAM SizeRecommended SwapWith Hibernation
≤ 2GB2x RAM3x RAM
2-8GBRAM size2x RAM
8-64GB0.5x RAM1.5x RAM
>64GB4GB minimum1x RAM

Custom Calculation Formula

For systems with specific requirements:

# Python formula for swap calculation
def calculate_swap(ram_gb):
    if ram_gb <= 2:
        return ram_gb * 2
    elif ram_gb <= 8:
        return ram_gb
    elif ram_gb <= 64:
        return max(ram_gb * 0.5, 4)
    else:
        return max(ram_gb * 0.25, 4)

Step 1: Create the Swap File

Create a 2GB swap file (adjust size as needed):

sudo fallocate -l 2G /swapfile

Alternative method using dd (slower but more compatible):

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

Step 2: Secure the Swap File

Set proper permissions to prevent unauthorized access:

sudo chmod 600 /swapfile

Verify permissions:

ls -lh /swapfile

Step 3: Set Up the Swap Space

Format the file as swap:

sudo mkswap /swapfile

Enable the swap file:

sudo swapon /swapfile

Step 4: Make Swap Permanent

Add to /etc/fstab for automatic mounting:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Verify the entry:

tail -1 /etc/fstab

Method 2: Creating a Swap Partition

If you prefer a dedicated partition:

Step 1: Create Partition

Use fdisk or parted to create a new partition:

sudo fdisk /dev/sdb

Step 2: Format as Swap

sudo mkswap /dev/sdb1

Step 3: Enable Swap Partition

sudo swapon /dev/sdb1

Step 4: Add to fstab

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

Optimizing Swap Performance

Configuring Swappiness

Swappiness controls how aggressively the kernel swaps:

  • 0: Avoid swapping (may cause OOM)
  • 1: Minimum swapping
  • 10: Recommended for desktops
  • 60: Default Ubuntu value
  • 100: Aggressive swapping

Check current swappiness:

cat /proc/sys/vm/swappiness

Set swappiness temporarily:

sudo sysctl vm.swappiness=10

Make swappiness permanent:

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

Cache Pressure Tuning

Adjust how the kernel reclaims cache:

# Default is 100, lower values preserve cache longer
sudo sysctl vm.vfs_cache_pressure=50
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf

Verification and Monitoring

Verify Swap Status

Check if swap is active:

sudo swapon --show
free -h
cat /proc/meminfo | grep Swap

Monitor Swap Usage

Real-time monitoring:

# Using htop
sudo apt install htop
htop

# Using vmstat
vmstat 1

# Check swap usage per process
for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n | tail

System Performance

Monitor overall system performance:

iostat -x 1
sar -r 1

Troubleshooting Common Issues

Swap File Creation Fails

Issue: fallocate not working Solution: Use dd method instead:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

Issue: Insufficient disk space Solution: Check available space and reduce swap size:

df -h /

Permission Errors

Issue: Swap file accessible by others Solution: Fix permissions:

sudo chmod 600 /swapfile
sudo chown root:root /swapfile

Performance Issues

Issue: System slow with swap Solutions:

  1. Reduce swappiness:
sudo sysctl vm.swappiness=1
  1. Add more RAM if budget allows

  2. Use SSD for swap file location

Boot Issues

Issue: System won’t boot after adding swap Solution: Boot from live USB and edit /etc/fstab:

sudo nano /etc/fstab
# Comment out the swap line with #

Advanced Configuration

Multiple Swap Files

You can have multiple swap areas:

sudo fallocate -l 1G /swapfile1
sudo fallocate -l 1G /swapfile2
sudo chmod 600 /swapfile1 /swapfile2
sudo mkswap /swapfile1
sudo mkswap /swapfile2
sudo swapon /swapfile1
sudo swapon /swapfile2

Swap Priority

Set different priorities for swap areas:

sudo swapon -p 10 /swapfile1  # Higher priority
sudo swapon -p 5 /swapfile2   # Lower priority

In /etc/fstab:

/swapfile1 none swap sw,pri=10 0 0
/swapfile2 none swap sw,pri=5 0 0

Encrypted Swap

For enhanced security:

sudo apt install cryptsetup
sudo cryptsetup luksFormat /dev/sdb1
sudo cryptsetup luksOpen /dev/sdb1 cryptswap
sudo mkswap /dev/mapper/cryptswap
sudo swapon /dev/mapper/cryptswap

Removing Swap Space

Disable and Remove Swap File

# Disable swap
sudo swapoff /swapfile

# Remove from fstab
sudo sed -i '/\/swapfile/d' /etc/fstab

# Delete the swap file
sudo rm /swapfile

Remove Swap Partition

# Disable swap partition
sudo swapoff /dev/sdb1

# Remove from fstab
sudo sed -i '/\/dev\/sdb1/d' /etc/fstab

# Delete partition (optional)
sudo fdisk /dev/sdb

Security Considerations

File Permissions

Always ensure swap files have restricted permissions:

sudo chmod 600 /swapfile
sudo chown root:root /swapfile

Swap Encryption

For sensitive data, consider encrypted swap:

  • Use encrypted partitions
  • Configure random encryption keys
  • Ensure keys are not stored persistently

Monitoring Access

Monitor swap file access:

sudo lsof | grep swapfile

Performance Best Practices

SSD Optimization

If using SSD for swap:

# Reduce swap usage
echo 'vm.swappiness=1' | sudo tee -a /etc/sysctl.conf

# Enable TRIM support
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf

RAID Configuration

For high-availability systems:

  • Use RAID 1 for swap partitions
  • Distribute swap across multiple drives
  • Monitor RAID health regularly

Regular Maintenance

  1. Monitor Usage: Check swap utilization weekly
  2. Performance Review: Assess if swap size is adequate
  3. Health Checks: Verify file integrity monthly
  4. Updates: Keep system updated for swap improvements

Automation Scripts

Swap Creation Script

#!/bin/bash
# create_swap.sh - Automated swap creation

SWAP_SIZE=${1:-2G}
SWAP_FILE="/swapfile"

echo "Creating ${SWAP_SIZE} swap file..."

# Create swap file
sudo fallocate -l $SWAP_SIZE $SWAP_FILE
sudo chmod 600 $SWAP_FILE
sudo mkswap $SWAP_FILE
sudo swapon $SWAP_FILE

# Add to fstab
if ! grep -q "$SWAP_FILE" /etc/fstab; then
    echo "$SWAP_FILE none swap sw 0 0" | sudo tee -a /etc/fstab
fi

echo "Swap space created successfully!"
free -h

Monitoring Script

#!/bin/bash
# monitor_swap.sh - Swap monitoring

SWAP_USAGE=$(free | grep Swap | awk '{print ($3/$2)*100}')
THRESHOLD=75

if (( $(echo "$SWAP_USAGE > $THRESHOLD" | bc -l) )); then
    echo "WARNING: Swap usage is ${SWAP_USAGE}%" | mail -s "High Swap Usage" [email protected]
fi

Conclusion

Adding swap space to Ubuntu provides essential virtual memory support for system stability and performance. Key takeaways:

  • Calculate appropriate swap size based on RAM and usage patterns
  • Use swap files for flexibility or partitions for performance
  • Optimize swappiness for your workload (10 for desktops, 1 for servers)
  • Monitor regularly to ensure optimal performance
  • Consider SSD placement for better swap performance
  • Secure swap files with proper permissions
  • Plan for growth - swap can be resized as needed

Proper swap configuration prevents out-of-memory conditions and provides a buffer for memory-intensive operations. Regular monitoring ensures your system maintains optimal performance as workloads change.