Add Swap To Linux
Running out of memory on your Linux server can bring your applications to a grinding halt. I recently experienced this firsthand when my AWS t3.small instance started freezing up during peak usage periods. After some investigation, I discovered the culprit: my 2GB instance was completely maxed out on RAM with no swap space configured as a safety net.
If you’re experiencing similar performance issues or want to proactively prevent memory-related problems, adding swap space is a straightforward solution that can make a significant difference in system stability.
What is Swap Space?
Swap space acts as virtual memory extension for your system. When your physical RAM becomes full, the Linux kernel can temporarily move less frequently used memory pages to swap space on your storage device. While accessing swap is slower than RAM, it prevents your system from running out of memory entirely and crashing applications.
When Do You Need Swap?
You should consider adding swap if:
- Your system frequently uses most or all available RAM
- You’re running memory-intensive applications
- You want to enable hibernation (swap should be at least equal to RAM size)
- You’re on a budget cloud instance with limited memory
- You want a safety buffer against memory spikes
Step-by-Step Guide to Adding Swap
1. Check Current Memory and Swap Usage
Before making changes, let’s see what we’re working with:
free -h
This command shows your current memory usage in human-readable format. If the “Swap” row shows all zeros, you don’t have any swap configured.
2. Create the Swap File
We’ll create a 2GB swap file using fallocate
, which is faster than the traditional dd
method:
sudo fallocate -l 2G /swapfile
The -l
flag specifies the size (2G = 2 gigabytes). You can adjust this based on your needs. A common rule of thumb is:
- 1-2GB RAM: Swap = 2x RAM
- 2-8GB RAM: Swap = 1x RAM
- 8GB+ RAM: Swap = 0.5x RAM or 4GB minimum
3. Secure the Swap File
Swap files should only be accessible by root for security reasons:
sudo chmod 600 /swapfile
This sets read/write permissions for root only and removes all access for other users.
4. Format the File as Swap
Convert the regular file into swap format:
sudo mkswap /swapfile
This command prepares the file to be used as swap space and will display the swap size confirmation.
5. Enable the Swap File
Activate the swap file immediately:
sudo swapon /swapfile
Your system can now start using the swap space right away.
6. Make It Permanent
To ensure the swap file is automatically mounted after reboots, add it to /etc/fstab
:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
This appends the swap configuration to your filesystem table.
7. Verify the Setup
Check that everything is working:
free -h
You should now see your swap space listed and available.
Optimizing Swap Performance
Swappiness Setting
The swappiness
parameter controls how aggressively the kernel swaps memory pages. The default value is usually 60, but you might want to adjust it:
# Check current swappiness
cat /proc/sys/vm/swappiness
# Set swappiness to 10 (less aggressive swapping)
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
Lower values (1-10) make the kernel avoid swapping unless absolutely necessary, while higher values (60-100) make it swap more readily.
Cache Pressure
You can also tune how the kernel reclaims memory used for caching:
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
Monitoring Your Swap Usage
Keep an eye on swap usage with these commands:
# Quick overview
free -h
# Detailed swap information
swapon --show
# Real-time monitoring
htop
Removing Swap (If Needed)
If you ever need to remove the swap file:
# Disable swap
sudo swapoff /swapfile
# Remove from fstab
sudo sed -i '/swapfile/d' /etc/fstab
# Delete the file
sudo rm /swapfile
Troubleshooting Common Issues
“Cannot allocate memory” errors: Your swap might be full. Check usage with free -h
and consider increasing swap size or optimizing your applications.
Slow performance: If your system is constantly swapping, you might need more RAM rather than more swap. Heavy swap usage indicates memory pressure.
Boot issues: If you have problems after adding swap, boot into recovery mode and check your /etc/fstab
entry for typos.
Alternative: Swap Partition vs Swap File
While this guide covers swap files, you can also create a dedicated swap partition. Swap files are generally more flexible since you can easily resize or remove them, while partitions might offer slightly better performance.