Swap File on Linux
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.
02
Check current swap
bash
# Swap status
free -h
swapon --show
# Swap usage per process
cat /proc/meminfo | grep -i swap
03
Create a swap file
Recommended size
| RAM available | Recommended swap |
|---|---|
| 512 MB - 1 GB | 1-2 GB |
| 2 GB | 2 GB |
| 4 GB | 2-4 GB |
| 8 GB+ | 2 GB (rarely need more) |
Procedure
bash
# 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
04
Make swap permanent
Add it to /etc/fstab to activate it on every reboot:
bash
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
# Verify /etc/fstab is correct
cat /etc/fstab | grep swap
05
Adjust swappiness
vm.swappiness controls how aggressively the kernel uses swap (0-100):
bash
# 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
- 0 = use swap only if RAM is completely full
- 10 = recommended for VPS (rarely uses swap)
- 60 = default Ubuntu (too aggressive for server)
06
Adjust cache pressure
bash
# 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
07
Resize swap
bash
# 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
08
Remove swap
bash
sudo swapoff /swapfile
sudo rm /swapfile
# Remove the line from /etc/fstab
sudo sed -i '/swapfile/d' /etc/fstab
09
Swap on partition (alternative)
If you have an additional disk or free partition:
bash
# 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
Gerelateerde artikelen
Server Management
Server Reboot
How to properly restart your VPS or VDS, both via SSH and from the control panel
2 min lezen
Server Management
Resource Monitoring
How to check CPU, RAM, disk and network on your server in real time
2 min lezen
Server Management
Disk Management
How to check disk space, find large files and free up disk space
2 min lezen
