How can I forget you, my dear swapfile, in a new VPS? You’re my first date every time. I love you so much, I give you the same size as RAM. Sometimes double, when I’m feeling generous.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Create 4GB swap file (adjust size as needed)
sudo fallocate -l 4G /swapfile

# Set permissions (critical for security)
sudo chmod 600 /swapfile

# Format as swap
sudo mkswap /swapfile

# Enable swap
sudo swapon /swapfile

# Verify
sudo swapon --show
free -h

Method 2: dd (traditional, slower but universal)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Create 4GB swap file
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress

# Set permissions
sudo chmod 600 /swapfile

# Format as swap
sudo mkswap /swapfile

# Enable swap
sudo swapon /swapfile

# Verify
free -h

Make it permanent (survives reboot)

1
2
3
4
5
# Backup fstab first (always!)
sudo cp /etc/fstab /etc/fstab.bak

# Add swap entry
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
1
2
3
4
5
6
7
8
# Check current value
cat /proc/sys/vm/swappiness

# Set to 10 (less aggressive, good for servers)
sudo sysctl vm.swappiness=10

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

Common sizes (my rule of thumb)

RAMSwap SizeWhy
512MB - 2GBSame as RAMVPS needs breathing room
4GB - 8GBSame as RAMPerfect balance
16GB+8GB or halfYou probably don’t need more

Remove swap (when you upgrade RAM)

1
2
3
4
5
6
7
8
# Disable swap
sudo swapoff /swapfile

# Remove file
sudo rm /swapfile

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

Quick verification commands

1
2
3
4
5
6
7
8
# Show swap usage
free -h

# Detailed swap info
sudo swapon --show

# Check if swap is in fstab
grep swap /etc/fstab

Pro tip: On cloud VPS with limited disk, swap = peace of mind. On SSD-backed instances, swap won’t kill performance. On HDD… well, at least your server won’t crash.