HOW-TO: Add Swap Space to Ubuntu/Debian
Complete guide to adding swap space on Ubuntu and Debian systems. Learn to create swap files or partitions, configure swappiness, monitor swap usage, and troubleshoot performance issues.
HOW-TO: Add Swap Space to Ubuntu/Debian
Overview
Swap space is disk-based virtual memory that allows your system to extend available RAM. When physical RAM is full, the kernel can move less-used memory pages to swap, freeing up RAM for active processes. This guide shows you how to add swap space on Ubuntu and Debian systems.
What you'll learn:
- Check current swap configuration
- Create a swap file (recommended for flexibility)
- Create a swap partition (for fresh installations)
- Enable and disable swap
- Configure swappiness (swap aggressiveness)
- Monitor swap usage
- Troubleshoot swap performance
Why swap matters:
- Prevents out-of-memory (OOM) crashes
- Allows graceful degradation under load
- Useful for systems with limited RAM (VPS, laptops, Raspberry Pi)
- Performance trade-off: disk is slower than RAM, but something is better than nothing
Prerequisites
Check Your System
# Verify you're on Ubuntu/Debian
cat /etc/os-release | grep -E "^(NAME|VERSION)="
# Output should include: Ubuntu or Debian
# Check your current user permissions
id
# You should see "uid=0(root)" or be able to sudo
Required Permissions
All swap operations require root privileges or sudo access. You'll use sudo throughout this guide.
Verify Current Swap
# Check current swap usage
free -h
# Output example:
# total used free shared buff/cache available
# Mem: 3.9Gi 2.1Gi 1.3Gi 102Mi 1.2Gi 1.5Gi
# Swap: 2.0Gi 512Mi 1.5Gi
# List swap devices/files
swapon --show
# Output example:
# NAME TYPE SIZE USED PRIO
# /swapfile file 2.0G 512.0M -2
If Swap: 0B, you have no swap configured yet.
Method 1: Create a Swap File (Recommended)
Creating a swap file is flexible, easy to resize, and doesn't require repartitioning. This is the preferred method for most users.
Step 1: Choose Swap Size
General recommendations:
- Small RAM (<2GB): Swap = 2× RAM
- Medium RAM (2-8GB): Swap = RAM size
- Large RAM (>8GB): Swap = 0.5× to 1× RAM (optional)
- Minimum: 1–2 GB swap is recommended
Examples:
- 512 MB RAM system → 1–2 GB swap
- 2 GB RAM system → 2–4 GB swap
- 8 GB RAM system → 4–8 GB swap
Calculate available disk space:
# Check available disk space
df -h /
# Output example:
# Filesystem Size Used Avail Use% Mounted on
# /dev/sda1 50G 20G 30G 40% /
Ensure you have at least 2–4 GB free space.
Step 2: Create the Swap File
Create a file that will hold swap data:
# Create a 4 GB swap file (adjust size as needed)
sudo fallocate -l 4G /swapfile
# Verify the file was created
ls -lh /swapfile
# Output: -rw-r--r-- 1 root root 4.0G Apr 10 10:00 /swapfile
Alternative (older systems):
If fallocate is unavailable, use dd:
sudo dd if=/dev/zero of=/swapfile bs=1G count=4
# count=4 means 4 GB (adjust as needed)
Step 3: Set Correct Permissions
Swap files must be readable only by root for security:
# Set permissions to 600 (read/write for owner only)
sudo chmod 600 /swapfile
# Verify permissions
ls -lh /swapfile
# Output: -rw------- 1 root root 4.0G Apr 10 10:00 /swapfile
Step 4: Format as Swap Space
Initialize the file as a Linux swap area:
# Set up the swap file
sudo mkswap /swapfile
# Output example:
# Setting up swapspace version 1.
# no label, UUID=abc123def456
Step 5: Enable Swap
Activate the swap file immediately:
# Turn on swap
sudo swapon /swapfile
# Verify it's active
swapon --show
# Output:
# NAME TYPE SIZE USED PRIO
# /swapfile file 4.0G 0B -2
Step 6: Make Swap Persistent
Add the swap file to /etc/fstab so it persists after reboot:
# Backup fstab first
sudo cp /etc/fstab /etc/fstab.bak
# Add swap file entry to fstab
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
# Verify it was added
cat /etc/fstab | grep swap
# Output: /swapfile none swap sw 0 0
Step 7: Verify Persistent Configuration
Test that swap will load on reboot:
# Check the entry is correct
cat /etc/fstab | tail -5
# Verify fstab syntax is valid
sudo mount -a
# No output = success
Method 2: Create a Swap Partition
Creating a dedicated swap partition is useful when installing a fresh system or reorganizing disk layout. This method provides better performance and isolation.
Step 1: Identify Available Disk Space
# List all disks and partitions
lsblk
# Output example:
# NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
# sda 8:0 0 50G 0 disk
# ├─sda1 8:1 0 40G 0 part /
# └─sda2 8:2 0 10G 0 part [SWAP]
# Or use fdisk for detailed view
sudo fdisk -l | head -30
Important: Only proceed if you have unallocated space or can safely shrink an existing partition. Back up your data first.
Step 2: Create a New Partition
Using fdisk (interactive tool):
# Open fdisk on your target disk (example: /dev/sda)
sudo fdisk /dev/sda
# Inside fdisk, enter commands:
# n → Create new partition
# p → Primary (or l for logical)
# [Enter] → Use default partition number
# [Enter] → Use default first sector
# +4G → Allocate 4 GB for swap (adjust size)
# t → Change partition type
# 82 → Linux swap (or search for "swap")
# w → Write changes and exit
Full fdisk session example:
Command (m for help): n
Partition type
p primary (0 primary, 0 extended, 4 free)
e extended (container for logical partitions)
Select (default p): p
Partition number (1-4, default 1):
First sector (2048-104857599, default 2048):
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-104857599, default 104857599): +4G
Created a new partition 1 of type 'Linux' and of size 4 GiB.
Command (m for help): t
Selected partition 1
Partition type or alias (type L to list all): 82
Changed type of partition 1 to 'Linux swap / Solaris'.
Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.
Step 3: Format the Partition as Swap
# Initialize the new partition as swap
sudo mkswap /dev/sdaX
# Replace sdaX with your partition identifier (e.g., /dev/sda3)
# Output example:
# Setting up swapspace version 1.
# no label, UUID=xyz789abc123
Step 4: Enable the Swap Partition
# Activate the partition
sudo swapon /dev/sdaX
# Verify it's active
swapon --show
Step 5: Make Swap Partition Persistent
Add the partition to /etc/fstab:
# Get the UUID of the swap partition
sudo blkid /dev/sdaX | grep -o 'UUID="[^"]*"'
# Output: UUID="abc123-def456-ghi789"
# Add to fstab (use UUID for reliability)
echo 'UUID=abc123-def456-ghi789 none swap sw 0 0' | sudo tee -a /etc/fstab
Configure Swappiness
Swappiness controls how aggressively the kernel swaps memory. Range: 0–100.
- 0: Avoid swapping; use only when necessary (but may cause OOM)
- 10–30: Minimal swapping; prefer RAM (good for modern systems)
- 60: Balanced (default on most systems)
- 100: Aggressive swapping (avoid on most systems)
Check Current Swappiness
# View current swappiness value
cat /proc/sys/vm/swappiness
# Output: 60 (typical default)
Adjust Swappiness Temporarily
# Set swappiness to 30 (less aggressive)
sudo sysctl vm.swappiness=30
# Verify change
cat /proc/sys/vm/swappiness
# Output: 30
This change is lost on reboot.
Adjust Swappiness Permanently
# Open sysctl config file
sudo nano /etc/sysctl.conf
# Add or modify this line at the end:
vm.swappiness=30
# Save (Ctrl+O, Enter, Ctrl+X in nano)
# Apply changes
sudo sysctl -p
# Output: vm.swappiness = 30
Recommended Settings
- Desktop/laptop with 4+ GB RAM: swappiness = 10–20
- Server with 8+ GB RAM: swappiness = 5–10
- Low-memory system (VPS, Pi): swappiness = 30–60
- Database servers: swappiness = 1–5 (avoid swap interference)
Monitor Swap Usage
Real-Time Swap Monitoring
# Show current swap usage in human-readable format
free -h
# Output:
# total used free shared buff/cache available
# Mem: 3.9Gi 2.1Gi 1.3Gi 102Mi 1.2Gi 1.5Gi
# Swap: 4.0Gi 256Mi 3.7Gi
# Watch swap usage continuously
watch -n 1 free -h
# Refreshes every 1 second (Ctrl+C to exit)
# Show detailed swap information
swapon --show
Per-Process Swap Usage
# Find which processes are using swap
for file in /proc/*/status; do
awk '/VmSwap|Name/{printf $2 " " $3}END{print ""}' "$file" | grep -v "0 kB"
done
# Output example:
# firefox 45876 kB
# chrome 234567 kB
Swap Activity Log
# Enable swap accounting (requires kernel parameter)
cat /proc/sys/vm/swap_ratio
# If 0, swap accounting is disabled
# View swap statistics
vmstat 1 5
# Output: Shows paging in (si) and out (so) rates
Troubleshooting
Issue: "swapon: cannot open /swapfile: No such file or directory"
Cause: Swap file doesn't exist.
Solution:
# Verify the swap file exists
ls -lh /swapfile
# If missing, recreate it (see Method 1, Step 2)
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Issue: "swapon: /swapfile: Permission denied"
Cause: Incorrect file permissions.
Solution:
# Fix permissions (must be 600)
sudo chmod 600 /swapfile
# Verify
ls -lh /swapfile
# Output: -rw------- 1 root root 4.0G
Issue: System is very slow or freezing (high swap usage)
Cause: System is using too much swap, causing disk thrashing (slow I/O).
Solutions:
- Increase available RAM (hardware upgrade)
- Reduce memory-heavy applications (close browsers, services)
- Lower swappiness value to minimize swap use:
sudo sysctl vm.swappiness=5 sudo nano /etc/sysctl.conf # Make permanent - Ensure disk is healthy:
sudo smartctl -a /dev/sda # Check disk health
Issue: Swap doesn't persist after reboot
Cause: Missing or incorrect /etc/fstab entry.
Solution:
# Check fstab for swap entry
cat /etc/fstab | grep swap
# If missing, add it (use UUID for reliability):
sudo blkid | grep swap # Find UUID
echo 'UUID=<uuid> none swap sw 0 0' | sudo tee -a /etc/fstab
# Verify fstab syntax
sudo mount -a
# Reboot and test
sudo reboot
swapon --show # Should show your swap after boot
Issue: "Not enough space for swap file"
Cause: Not enough free disk space.
Solution:
# Check disk usage
df -h
# Free up space by:
# - Removing old log files
sudo journalctl --vacuum=50M # Limit journal to 50 MB
# - Cleaning package manager cache
sudo apt clean && sudo apt autoclean
# - Removing temp files
sudo rm -rf /tmp/*
Issue: Cannot increase swap size
Cause: Existing swap file/partition is in use.
Solution:
- Disable swap:
sudo swapoff -a - Remove old swap file or partition
- Create new swap with desired size (see Method 1 or 2)
- Re-enable:
sudo swapon -a
Best Practices
✅ Do:
- Start with 1–2 GB minimum — provides safety buffer
- Use swap files on modern systems — more flexible than partitions
- Set permissions to 600 — prevents unauthorized access
- Monitor usage regularly — watch for excessive swapping
- Test configuration before rebooting — verify fstab syntax
- Keep disk defragmented — ensures swap performance
- Use UUID in fstab — more reliable than device names
❌ Don't:
- Use swap on slow storage — consider SSD/NVMe for better performance
- Ignore persistent configuration — swap won't survive reboot without fstab entry
- Set swappiness to 0 — may cause OOM crashes
- Fill swap beyond 50% — indicates memory pressure; consider RAM upgrade
- Delete swap files without disabling first — causes errors
- Use multiple swap devices on the same disk — no performance benefit
Verification Checklist
After completing this guide, verify your setup:
# ✓ Swap is active
free -h | grep -i swap
# ✓ Swap file/partition is listed
swapon --show
# ✓ fstab has correct entry
cat /etc/fstab | grep swap
# ✓ Swappiness is set as desired
cat /proc/sys/vm/swappiness
# ✓ Disk space is sufficient
df -h /
# ✓ System boots normally (optional, after reboot)
sudo reboot
# Then: swapon --show
All checks pass = swap is properly configured! ✅
Resources
- Linux Swap Official Docs: https://wiki.debian.org/Swap
- Ubuntu Swap Guide: https://help.ubuntu.com/community/SwapFaq
- Kernel Swap Parameters: https://www.kernel.org/doc/html/latest/admin-guide/mm/index.html
- Performance Tuning: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/performance_tuning_guide/
See Also
- Howto Install Rust Linux — Setting up development environment on Linux
- Howto Ripgrep Install Use — Finding files efficiently on disk-constrained systems