LochStudios  /  Help Centre  /  VPS & Linux  /  Add Swap Space to Your VPS

Add Swap Space to Your VPS

Configure swap space on your Ubuntu/Debian VPS to prevent out-of-memory crashes when RAM is exhausted.

Updated

Swap is disk space that the kernel uses as an overflow when physical RAM is full. It's slower than RAM but prevents your VPS from crashing when memory runs out. This guide shows how to add or expand swap on a live Ubuntu/Debian server without downtime.

Prerequisites

  • Ubuntu 18.04+ or Debian 10+
  • SSH access with sudo privileges
  • A few gigabytes of free disk space

Check current swap

First, see what swap you currently have:

free -h

Look for the Swap: row. If it shows 0B, you have no swap.

Also check swap usage:
CODE1

Step 1: Create a swap file (recommended for VPS)

Creating a file (rather than a partition) is flexible and works on any VPS. Let's create a 2 GB swap file:

sudo fallocate -l 2G /swapfile

If fallocate is not available, use dd instead:
CODE3

Step 2: Set correct permissions

Swap files must be readable only by root:

sudo chmod 600 /swapfile

Step 3: Initialize the swap file

sudo mkswap /swapfile

Step 4: Enable the swap file

sudo swapon /swapfile

Step 5: Verify swap is active

free -h

You should now see your 2 GB swap in the output.

Also verify it's in the active list:
CODE8

Step 6: Make swap persistent across reboots

Add the swap file to /etc/fstab so it's activated automatically:

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

Verify the entry was added:
CODE10

Step 7 (Optional): Adjust swappiness

Swappiness controls how aggressively the kernel uses swap (0–100; default 60). Lower values prioritize keeping data in RAM:

Check current swappiness:
CODE11

To set it to 10 (use swap only when necessary):
CODE12

To make this permanent, add it to /etc/sysctl.conf:
CODE13

Expanding existing swap

If you already have swap and need more, you can add an additional swap file:

sudo fallocate -l 2G /swapfile2
sudo chmod 600 /swapfile2
sudo mkswap /swapfile2
sudo swapon /swapfile2
echo '/swapfile2 none swap sw 0 0' | sudo tee -a /etc/fstab

Removing swap (if not needed)

To disable a swap file:

sudo swapoff /swapfile

Then remove the entry from /etc/fstab:
CODE16

And optionally delete the file:
CODE17

Tips

  • Size guideline: For a VPS with 1–2 GB RAM, 2–4 GB swap is reasonable. For 4+ GB RAM, you may not need swap at all (swap is a fallback, not a substitute for RAM).
  • Performance: Swap is much slower than RAM. If you're hitting swap regularly, consider upgrading your VPS RAM instead.
  • Monitoring: Watch swap usage with free -h or vmstat 1 (updates every 1 second). High swap usage signals you need more RAM.
  • Multiple files: You can have multiple swap files for redundancy or incremental growth.

Swap is now configured and will persist across reboots.


Was this article helpful?

← Back to VPS & Linux