Server Management

Swap File on Linux

How to create and configure a swap file to prevent crashes from out-of-memory on Linux VPS

Swap is disk space used as virtual memory when RAM is full. On VPS with little RAM (1-2 GB) it is essential to prevent critical processes from crashing (OOM Killer).

Swap on SSD is much slower than real RAM. It doesn't replace RAM, but prevents sudden crashes. For intensive workloads, the correct solution is to upgrade your plan.


Check current swap

# Swap status
free -h
swapon --show

# Swap usage per process
cat /proc/meminfo | grep -i swap

Create a swap file

RAM availableRecommended swap
512 MB - 1 GB1-2 GB
2 GB2 GB
4 GB2-4 GB
8 GB+2 GB (rarely need more)

Procedure

# 1. Create the file (e.g. 2 GB)
sudo fallocate -l 2G /swapfile

# If fallocate is not available:
# sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

# 2. Set correct permissions (only root can read)
sudo chmod 600 /swapfile

# 3. Format as swap
sudo mkswap /swapfile

# 4. Activate swap
sudo swapon /swapfile

# 5. Verify
free -h
swapon --show

Make swap permanent

Add it to /etc/fstab to activate it on every reboot:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Verify /etc/fstab is correct
cat /etc/fstab | grep swap

Adjust swappiness

vm.swappiness controls how aggressively the kernel uses swap (0-100):

  • 0 = use swap only if RAM is completely full
  • 10 = recommended for VPS (rarely uses swap)
  • 60 = default Ubuntu (too aggressive for server)
# See current value
cat /proc/sys/vm/swappiness

# Set to 10 (more conservative)
sudo sysctl vm.swappiness=10

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

Adjust cache pressure

# Reduces kernel's tendency to clear filesystem cache
sudo sysctl vm.vfs_cache_pressure=50
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf

Resize swap

# Disable current swap
sudo swapoff /swapfile

# Resize (e.g. to 4 GB)
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

# Verify
free -h

Remove swap

sudo swapoff /swapfile
sudo rm /swapfile

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

Swap on partition (alternative)

If you have an additional disk or free partition:

# Format the partition as swap
sudo mkswap /dev/sdb1

# Activate
sudo swapon /dev/sdb1

# Permanent in /etc/fstab
echo '/dev/sdb1 none swap sw 0 0' | sudo tee -a /etc/fstab

On this page