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 Size | Recommended Swap | With Hibernation |
---|---|---|
≤ 2GB | 2x RAM | 3x RAM |
2-8GB | RAM size | 2x RAM |
8-64GB | 0.5x RAM | 1.5x RAM |
>64GB | 4GB minimum | 1x 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)
Method 1: Creating a Swap File (Recommended)
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:
- Reduce swappiness:
sudo sysctl vm.swappiness=1
-
Add more RAM if budget allows
-
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
- Monitor Usage: Check swap utilization weekly
- Performance Review: Assess if swap size is adequate
- Health Checks: Verify file integrity monthly
- 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.