VPS Swap Configuration
Add persistent swap space to prevent OOM errors on memory-constrained VPS.
Quick Setup
# Create 4GB swap file
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# Make persistent across reboots
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Verify
swapon --show
free -h
Expected output:
NAME TYPE SIZE USED PRIO
/swapfile file 4G 0B -2
Size Guidelines
| RAM | Swap Size |
|---|---|
| 2GB | 2-4GB |
| 4GB | 2-4GB |
| 8GB+ | 2GB |
Adjust -l parameter: 1G, 2G, 4G, 8G
Tuning (Optional)
Swappiness (0-100, default 60): Lower = less aggressive swapping
# Check current
cat /proc/sys/vm/swappiness
# Set to 10 (conservative)
sudo sysctl vm.swappiness=10
# Make permanent
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
Recommended values:
- Desktop: 60 (default)
- Server: 10-30
- Database server: 1-10
Remove Swap
sudo swapoff /swapfile
sudo rm /swapfile
# Remove line from /etc/fstab
sudo sed -i '/swapfile/d' /etc/fstab
Troubleshooting
Swap not activating after reboot
# Check fstab entry
cat /etc/fstab | grep swap
# Manually activate
sudo swapon /swapfile
fallocate not supported (some filesystems)
# Use dd instead
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Check swap usage
free -h
htop # Press F6, sort by SWAP
Notes
- Swap file, not partition (easier management)
chmod 600required for security- Performance: Swap on SSD > HDD, but slower than RAM
- Cloud providers: Check if swap allowed (some restrict it)
- Docker builds: Common use case for 2-4GB VPS







