Back to site

Configure swap

Create a swap file with fallocate, enable it via fstab, and adjust swappiness.

Configure swap

Swap lets the kernel move rarely used memory pages to disk when RAM is full. On a HolyCloud VPS, a swap file is often enough; this guide covers fallocate, the fstab entry, and swappiness.

Prerequisites

  • Linux VPS (Ubuntu 22.04/24.04 or Debian 12)
  • sudo access
  • Free disk space (check with df -h)

Tip: on a VPS with 2 to 4 GB RAM, 1 to 2 GB swap is a good starting point. Avoid oversized swap on SSD if RAM is already sufficient.

Check current state

free -h
swapon --show
cat /proc/swaps

Create the swap file with fallocate

Choose a size (example: 2 GB):

sudo fallocate -l 2G /swapfile

If fallocate fails on some filesystems, use dd:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

Secure permissions and format:

sudo chmod 600 /swapfile
sudo mkswap /swapfile

Enable immediately:

sudo swapon /swapfile
swapon --show

Persistence in /etc/fstab

Back up fstab then add a line:

sudo cp -a /etc/fstab /etc/fstab.bak.$(date +%F)
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Test mounting without reboot:

sudo swapoff /swapfile
sudo swapon -a
free -h

Adjust swappiness

vm.swappiness controls how aggressively the kernel uses swap (0–100). Common server value: 10 (less aggressive); on tight small VPS: 30–60.

Check:

cat /proc/sys/vm/swappiness

Temporary change:

sudo sysctl vm.swappiness=10

Persistent:

echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system

Verification after reboot

sudo reboot
# après reconnexion SSH
swapon --show
grep swap /etc/fstab

Remove or resize swap

Disable and remove from fstab:

sudo swapoff /swapfile
sudo sed -i '\|/swapfile|d' /etc/fstab
sudo rm -f /swapfile

Troubleshooting

| Problem | Solution |

|----------|----------|

| swapon: /swapfile: insecure permissions | chmod 600 /swapfile |

| Swap not active at boot | Check line in /etc/fstab, systemctl status systemd-swapon |

| Extreme slowness | Lower swappiness or upgrade VPS RAM |

Need help?

HolyCloud support can advise if your workload needs a plan upgrade rather than a very large swap.