How to Add a Swap File on a Linux VPS

Every VPS plan advertises a fixed amount of RAM, and sooner or later something on that server needs more than the plan provides — a backup job, a batch import, a burst of concurrent requests that all land at once. Without a safety net, the kernel's out-of-memory handling starts ending processes to keep the system alive, and it doesn't always pick the process you'd have chosen. A swap file gives the kernel somewhere else to put memory pages before it gets to that point, and setting one up takes a handful of commands and about fifteen minutes. This guide creates a swap file, activates it, makes it survive a reboot, and tunes how eagerly the kernel actually reaches for it.

Quick Verdict
A swap file is a plain file on disk that the kernel treats as overflow memory once physical RAM is full. Creating one is four commands — fallocate or dd to allocate the file, chmod 600 to lock down its permissions, mkswap to format it, and swapon to activate it — plus one line in /etc/fstab so it survives a reboot. The size you choose and the swappiness value you set afterward matter more than the create step itself: swap is a buffer against a crash, not a substitute for RAM your workload genuinely needs.

What a Swap File Actually Does

Swap space is disk space the kernel uses as an extension of physical RAM: when memory pressure builds, the kernel moves inactive pages out of RAM and onto the swap area, freeing physical memory for whatever is actively running. The kernel's own memory-management documentation frames this as a paging mechanism rather than the older "copy the whole process" model the term originally described, though the convention of calling it swapping has stuck regardless, per the kernel's swap management chapter. Two things make it useful even on a server with plenty of disk free: it lets a workload survive a temporary memory spike instead of triggering an out-of-memory kill, and pages a process only touches once during startup can be pushed to swap and never bother RAM again.

None of that makes swap fast — disk, even fast SSD-backed VPS storage, is far slower than RAM, and if a workload is continuously starved for memory, adding swap only delays the point where more RAM is the real fix. A swap file is the practical way most VPS plans add this safety net: Ubuntu 22.04 and later actually create a small swap file at /swapfile by default at install time rather than a dedicated swap partition, precisely because a file is easier to create, resize, or remove than a partition on a disk layout you don't fully control.

Checking What You're Working With

Before creating anything, check whether swap is already configured — some base images ship a small default:

1sudo swapon --show
2free -h

An empty swapon --show is your signal that no swap is active yet. free -h shows total, used, and available RAM alongside the Swap line, which is the number worth watching once swap is in use — heavy, sustained use there is a RAM-upgrade signal, not a reason to enlarge swap further. Confirm there's room for the file you're about to create, too:

1df -h

Check the Avail column on the / filesystem against the swap size you're planning.

Choosing a Swap File Size

There's no single correct number, but a workable starting rule is to size swap at roughly the installed RAM if the VPS has less than 2 GB, or about half of RAM if it has more — a 1 GB plan gets a 1 GB swap file, a 4 GB plan gets around 2 GB, per the standard sizing guidance most VPS swap guides use. A 2 GB file is a reasonable default if you'd rather skip the ratio math on a small general-purpose server. Whatever you land on, treat it as a stopgap: routinely filling that much swap means the plan needs more RAM, not a bigger file.

Creating the Swap File

Two commands allocate the file itself. fallocate pre-allocates blocks and is faster; dd writes the file byte by byte and is slower but guarantees the file isn't sparse, which matters on some filesystems. On a standard ext4-formatted VPS, fallocate is the usual choice:

1sudo fallocate -l 2G /swapfile

If it fails or isn't available, dd is the portable fallback for the same 2 GB, in 1 MiB chunks — the command sequence below mirrors the standard walkthrough for this task:

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

Lock the file down before formatting it — swap can hold copies of whatever was in RAM, so it shouldn't be world-readable:

1sudo chmod 600 /swapfile

Format it as a swap area and turn it on:

1sudo mkswap /swapfile
2sudo swapon /swapfile

The mkswap manual page notes it refuses to set up an area smaller than 10 pages, and that recent versions set the filesystem's no-copy-on-write attribute automatically when the file is created with mkswap's own --file option — relevant specifically for Btrfs, covered below. Confirm it's live:

1sudo swapon --show
2free -h

/swapfile should now show in both, with the allocated size on the Swap line.

Making It Survive a Reboot

A swap file turned on with swapon doesn't persist past a restart on its own — it needs an entry in /etc/fstab, the same file listing every other mounted filesystem on the server. Back it up, then add the line:

1sudo cp /etc/fstab /etc/fstab.bak
2echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

none stands in for a mount point (swap has none), swap is the filesystem type, sw the mount option, and 0 0 the dump and fsck-order flags — the standard form used across swap-file guides for this exact line. Test it without rebooting by turning swap off and re-enabling everything fstab lists:

1sudo swapoff /swapfile
2sudo swapon -a
3sudo swapon --show

If /swapfile reappears, the entry is correct and the file will come back on its own after a restart.

Tuning How Eagerly the Kernel Uses Swap

vm.swappiness controls how aggressively the kernel reaches for swap versus holding data in RAM. On current kernels the value can range from 0 to 200, though most practical tuning stays within 0–100: Ubuntu's out-of-the-box default is 60, a value of 10 or lower keeps the kernel off swap much longer, and 100 treats swap and RAM as roughly equal-cost. On a server — rather than a desktop that also uses swap for hibernation — lower swappiness generally means more predictable performance, since swap is meaningfully slower than RAM even on SSD-backed storage. A swappiness of 10 is a common starting point for a general-purpose or web-facing server; database servers are often tuned lower still, down toward 1–10, since a database's own buffer-cache logic usually manages memory better than the kernel's general heuristic.

Check and set it:

1cat /proc/sys/vm/swappiness
2sudo sysctl vm.swappiness=10

sysctl alone only changes the running value — it resets on reboot unless it's also written to a config file:

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

A related setting, vm.vfs_cache_pressure, controls how aggressively the kernel reclaims memory used for filesystem metadata caches rather than swap specifically. Lowering it from the default of 100 to around 50 makes the kernel hold onto those caches longer, which can help on file-heavy workloads, and it's set the same way in the same config file.

A Note on Btrfs Filesystems

If the VPS runs Btrfs rather than the more common ext4 or XFS, a plain swap file needs extra handling: Btrfs's copy-on-write behavior doesn't work correctly with a swap file by default, so the file needs the no-copy-on-write attribute applied — either via a dedicated subvolume created up front, or automatically, since a current mkswap sets that attribute itself when the file is created through its --file option. Worth checking your installed mkswap version supports that flag before assuming the older manual subvolume-plus-chattr workaround is still necessary.

Resizing or Removing a Swap File

Needs change — a VPS gets upgraded to more RAM, or the swap file turns out to be the wrong size. Resizing means recreating it rather than editing it in place: turn the file off, delete it, create a new one at the size you want, then repeat the format-and-activate steps:

1sudo swapoff /swapfile
2sudo rm /swapfile
3sudo fallocate -l 4G /swapfile
4sudo chmod 600 /swapfile
5sudo mkswap /swapfile
6sudo swapon /swapfile

Because the filename didn't change, the existing /etc/fstab line still applies. To remove swap entirely instead, turn it off, delete the file, and remove or comment out the fstab line so it doesn't try to re-enable a file that no longer exists.

Watching Swap Do Its Job

Once it's active, keep an eye on how much it's actually used rather than treating it as set-and-forget:

1watch -n 1 free -h
2vmstat 1 10

vmstat's si and so columns show swap-in and swap-out activity in real time. Brief spikes during a big job are normal; sustained high so values mean the server is under real, ongoing memory pressure, and enlarging swap further only buys a little time before performance suffers. At that point the honest fix is a bigger VPS plan, not a bigger swap file.

Who This Is Worth Doing For

Good fit:

  • Small-RAM VPS plans (512 MB–2 GB) where an occasional memory spike risks losing the wrong process
  • Backup, build, or import jobs that briefly need more headroom than the plan provides
  • Any server where a slow buffer beats a hard crash

Not the best fit:

  • Servers already showing sustained heavy swap use — that's a RAM-upgrade problem, not a tuning problem
  • High-throughput database servers where consistent low latency matters more than an emergency buffer, unless swappiness is tuned aggressively low
  • VPS plans with very limited disk space, where a multi-gigabyte swap file competes directly with data storage

Getting It Right the First Time

The whole setup is four commands to create and activate the file, one line in /etc/fstab to make it permanent, and one sysctl value to control how eagerly it gets used. None of it requires a config rewrite or a service restart, and it's just as easy to undo if a resize or removal turns out to be the better call later. Run swapon --show and free -h after each step, and you'll know immediately whether the swap file is doing what you set it up to do — a quiet safety net for the one memory spike that would otherwise have taken the server down.

References

Posts in this series