Add a swap file on a Linux VPS

Create a swap file, make it survive reboots, tune swappiness, and learn when swap helps and when you really need more RAM.

  • Beginner
  • Linux VPS
  • 2 min read

By RunRacks Team · Published

Swap is disk space the kernel can use when RAM runs out. On a small VPS it is a cushion that stops short memory spikes, such as a package upgrade or a build, from killing your database or web server.

1. Check what you have

Terminal
sudo swapon --show
free -h

If swapon prints nothing, there is no swap yet.

2. Create the file

1 to 2 GB is plenty for most small servers. This creates a 2 GB file:

Terminal
sudo fallocate -l 2G /swapfile

If fallocate fails or swapon later complains about holes in the file, create it with dd instead (slower, works everywhere):

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

3. Secure it and turn it on

Terminal
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
sudo swapon --show

4. Make it permanent

Add the swap file to /etc/fstab so it comes back after a reboot. Back the file up first, because a broken fstab can stop the server booting:

Terminal
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
sudo findmnt --verify

5. Tune swappiness

vm.swappiness controls how eagerly the kernel uses swap. For servers, a low value keeps active data in RAM:

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

Remove the swap file

Terminal
sudo swapoff /swapfile
sudo rm /swapfile

Then delete the /swapfile line from /etc/fstab.

Troubleshooting

  • swapon: read swap header failed / invalid argument: recreate the file with the dd command and run mkswap again.
  • Server will not boot after editing fstab: use the browser console from Open Control Panel and restore the backup: cp /etc/fstab.bak /etc/fstab.
  • Processes are still killed for memory: check journalctl -k | grep -i "out of memory" to see what was using it. See Monitor CPU, memory, disk and logs.

Next steps

Was this guide helpful?

Still stuck?

Ask RunRacks AI for a quick answer, or open a ticket and our team will take a look at your server.

Linux VPS

Deploy a Node.js app with PM2 behind Nginx

Install a Node.js LTS release, keep your app running with PM2 across crashes and reboots, and serve it through Nginx with HTTPS.

  • Intermediate
  • Linux VPS
  • 3 min read

Linux VPS

Create an SFTP-only user limited to one folder

Give someone file access over SFTP without a shell, locked inside one folder. Configure internal-sftp with a Match block, set the chroot ownership right and test with WinSCP.

  • Advanced
  • Linux VPS
  • 5 min read