How to Add Swap Space on Ubuntu (Swap File, Swap Partition, and Swappiness Tuning)

CodexFuse Team · 2026-11-04T06:13:13.527Z · 11 min read min read

When a Linux server runs out of memory, the kernel has two choices: kill something, or find somewhere else to park idle memory pages. Swap space is that somewhere else — a dedicated area on disk where the kernel can temporarily store data it can no longer hold in RAM. If you run a small virtual server, learning how to add swap space on Ubuntu is one of the cheapest insurance policies you can buy: it costs nothing, takes five minutes, and turns abrupt out-of-memory crashes into graceful slowdowns. This guide walks through the full swap-file arc on a modern Ubuntu system, the swap-partition route for completeness, how to pick a size, and how to tune swappiness like a server admin.

What Is Swap Space, and Why Does a VPS Need One?

Swap space is disk space the Linux kernel uses as an extension of physical memory. When RAM fills up, the kernel moves inactive pages out to swap, freeing RAM for active processes. On a desktop this keeps things responsive under load; on a what is VPS hosting instance with 1 or 2 GB of RAM, it is the difference between a slow build and a dead one.

The alternative to swap is the kernel's out-of-memory killer. "When RAM fills up on Ubuntu servers, the Linux out-of-memory killer can terminate processes and disrupt services," DigitalOcean's Ubuntu swap tutorial explains. "Adding swap space gives the kernel secondary storage for anonymous memory pages so workloads can degrade gracefully instead of failing abruptly."

This guide targets Ubuntu 26.04 LTS (Resolute Raccoon), the current long-term-support release as of November 2026 — Canonical released it on 23 April 2026 with standard security maintenance to May 2031, per Canonical's release-cycle page. The commands below apply equally to Ubuntu 22.04 and 24.04 LTS.

How Much Swap Space Should You Add?

Match the swap size to the RAM, not to the disk. Red Hat's RHEL 10 documentation publishes the clearest public sizing guideline, and its numbers are the sensible defaults for Ubuntu servers too:

Amount of RAMRecommended swap space
Less than 2 GiB2× RAM
2 GiB – 8 GiBEqual to RAM
8 GiB – 64 GiBAt least 4 GiB
More than 64 GiBWorkload-dependent, at least 4 GiB

Red Hat adds an important qualifier: "recommended swap space is considered a function of system memory workload, not system memory." A 1 GB VPS running a small web app gets a 2 GB swap file; an 8 GB build box gets 4 GB, not 8.

For the typical small VPS, a concrete rule works well: 1 GB RAM → 2 GB swap, 2 GB RAM → 4 GB swap, 4 GB RAM → 4 GB swap. The examples in this guide use a 2 GB swap file, and you can scale the size up or down by changing one number.

How Do You Add a Swap File on Ubuntu?

A swap file is the right choice on virtually every modern Ubuntu system — especially on a VPS, where you have no spare disk partition to give away. Follow these six steps in order:

  1. Check for existing swap. Run sudo swapon --show and free -h. If swap is already active (Ubuntu's installer often creates one), note the size before deciding whether you need more.
  2. Create the file. On ext4, the fast way is sudo fallocate -l 2G /swapfile. The fallocate man page explains that preallocation "is done quickly by allocating blocks and marking them as uninitialized, requiring no IO to the data blocks" — the file appears instantly.
  3. Lock down permissions. Run sudo chmod 600 /swapfile so the file is only accessible to root, as DigitalOcean's tutorial instructs.
  4. Format it as swap. Run sudo mkswap /swapfile. The mkswap man page states that it "sets up a Linux swap area on a device or in a file"; the tool confirms with "Setting up swapspace version 1".
  5. Activate it. Run sudo swapon /swapfile. The swapon man page describes it as the command "used to specify devices on which paging and swapping are to take place". Confirm with sudo swapon --show and free -h — you should see a Swap row of 2.0G.
  6. Make it permanent. Without an /etc/fstab entry, "the system will not enable this swap after a reboot," as DigitalOcean notes. Append the line /swapfile none swap sw 0 0 to /etc/fstab with echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab, then validate the file before rebooting with sudo findmnt --verify --verbose.

No reboot is needed: the swap is active immediately and will be re-enabled automatically after the next reboot.

Should You Use fallocate or dd to Create the Swap File?

Use fallocate on ext4 — and use dd everywhere else. The catch is documented in the NOTES section of the swapon(8) man page: "You should not use swapon on a file with holes." The kernel expects to write directly to the swap file without the filesystem's help, and on preallocated files — such as those made with fallocate(1) — on filesystems like XFS or ext4, or on copy-on-write filesystems like Btrfs, that assumption can break.

The man page's recommendation is explicit: "It is recommended to use dd(1) and /dev/zero to avoid holes on XFS and ext4." Newer util-linux versions call that the most portable solution overall, and Btrfs swap files are supported only since Linux 5.0 on files with the nocow attribute set.

If you are on XFS, Btrfs, or any filesystem you are unsure about, create the file the safe way instead:

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

Here bs=1M count=2048 yields 2 GiB. It writes real zeros instead of preallocating, so the file has no holes — at the cost of a slower creation and a one-time burst of disk writes.

How Do You Add a Swap Partition Instead?

A swap partition is the classic route: a dedicated disk partition formatted for swap. On a VPS you rarely have unpartitioned space, which is why the file approach won — but on bare metal or a server you installed yourself, the partition arc is three steps:

  1. Create the partition with fdisk (or gdisk for GPT disks) and set its type: MBR type code 82 for Linux swap, or GPT code 8200. Per the gdisk(8) man page, the GPT code is the MBR code times 0x0100.
  2. Format it: sudo mkswap /dev/sdXn (replacing /dev/sdXn with your partition). The mkswap man page confirms it "sets up a Linux swap area on a device or in a file".
  3. Enable it: sudo swapon /dev/sdXn, then persist it in /etc/fstab with /dev/sdXn none swap sw 0 0 — or better, reference it by UUID so the name can't shift.

Swap File vs Swap Partition: Which Should You Choose?

On a VPS there is no real contest, but it is worth seeing the trade-offs side by side:

Swap fileSwap partition
Needs spare disk spaceYes — any filesystem spaceYes — unpartitioned space only
Repartitioning requiredNoYes
Resize laterEasy (swapoff, recreate, swapon)Hard (move partitions)
Works on cloud VPSYesUsually impossible
PerformanceEssentially identical on ext4Essentially identical
Holes/CoW caveatsYes (fallocate vs dd)None

The file wins on every practical axis for virtual servers. Partitions remain the tidy answer for bare-metal installs where you control the partition table from day one.

How Do You Tune Swappiness on a Server?

Swappiness controls how aggressively the kernel moves memory pages to swap. The kernel documentation for /proc/sys/vm explains that the control "is used to define the rough relative IO cost of swapping and filesystem paging" and that "the default value is 60."

A default of 60 suits desktops. For servers, which should prefer RAM, the widely recommended value is 10: "For servers, a lower value such as 10 is often better so the kernel relies less on swap," per DigitalOcean's tutorial. Apply it immediately:

sudo sysctl vm.swappiness=10

That change lasts until reboot. To make the vm.swappiness setting permanent on Ubuntu 22.04 and later, store it under /etc/sysctl.d/:

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

A second knob worth knowing is vm.vfs_cache_pressure. The kernel docs say this value "controls the tendency of the kernel to reclaim the memory which is used for caching of directory and inode objects," and that at the default 100 "the kernel will attempt to reclaim dentries and inodes at a 'fair' rate with respect to pagecache and swapcache reclaim." On I/O-heavy servers, lowering it to 50 makes the kernel retain filesystem metadata longer: sudo sysctl vm.vfs_cache_pressure=50.

How Do You Remove Swap Safely?

To remove a swap file permanently, follow this order — delete the fstab line first, then deactivate, then delete the file:

  1. Remove the /swapfile line from /etc/fstab.
  2. Deactivate it: sudo swapoff /swapfile. The swapon(8) man page describes swapoff as the command that "disables swapping on the specified devices and files."
  3. Delete the file: sudo rm /swapfile.

One caution from DigitalOcean's tutorial applies here: do not run swapoff on a system that is actively under memory pressure without checking free -h first — deactivating swap while RAM is nearly full can trigger the very OOM kills you were avoiding.

What to Do When Your VPS Keeps Using Swap

Swap working as intended looks like a Swap row that sits near 0B used most of the time and fills only during heavy moments — a build, a backup, a traffic spike. Swap that stays heavily used means the server is chronically short of RAM.

The honest fix, in DigitalOcean's own words: "Reads and writes to swap are slower than DRAM, so swap is a safety net, not a substitute for enough RAM for steady-state load." And the companion rule: "If the server regularly hits swap, the right fix is to upgrade RAM, not to add more swap."

That usually means one of three moves: resize the VPS to a plan with more RAM, move to a managed VPS guide setup where someone else watches the memory graphs, or find what is eating the memory — a leaky app, a Docker beginner guide container stack left running, or a process bound to a port it shouldn't be on (a good moment to check open ports on your VPS as part of the same hygiene pass).

Sources

  • Canonical — "Ubuntu release cycle" (26.04 LTS, 23 April 2026; support to May 2031): https://ubuntu.com/about/release-cycle
  • fallocate(1) man page (util-linux): https://man7.org/linux/man-pages/man1/fallocate.1.html
  • swapon(8) man page (NOTES on files with holes; swapoff description): https://manpages.debian.org/experimental/mount/swapon.8.en.html
  • mkswap(8) man page: https://manpages.ubuntu.com/manpages/noble/man8/mkswap.8.html
  • Red Hat Enterprise Linux 10 documentation — "Getting started with swap" (sizing table): https://docs.redhat.com/pt-br/documentation/red_hat_enterprise_linux/10/html/managing_storage_devices/getting-started-with-swap
  • Linux kernel documentation — /proc/sys/vm (swappiness default 60; vfs_cache_pressure default 100): https://www.kernel.org/doc/html/latest/admin-guide/sysctl/vm.html
  • DigitalOcean — "How To Add Swap Space on Ubuntu" (22.04 tutorial; OOM context, fstab, sysctl.d persistence): https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-22-04
  • DigitalOcean — "How To Add Swap Space on Ubuntu 20.04" (swappiness=10; safety-net wording): https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-20-04
  • gdisk(8) man page (GPT type code 8200): https://manpages.ubuntu.com/manpages/trusty/en/man8/gdisk.8.html

Frequently Asked Questions

Can I add swap space without rebooting?

Yes. Create the file, run mkswap and swapon, and add the entry to /etc/fstab. Swap is active immediately and will be re-enabled automatically after the next reboot.

How do I check whether swap is already enabled?

Run sudo swapon --show to list active swap devices and files, and free -h to see the totals, including the Swap row. Always check before adding more — Ubuntu's installer often provisions a swap file by default.

Why does my swap show 0B used even though it is enabled?

That is normal and healthy. The kernel only moves pages to swap under memory pressure, and with a low swappiness setting (like 10) it strongly prefers RAM. Swap sitting at 0B used is exactly what you want on an idle server — it is insurance, not fuel.

What does vm.swappiness=10 actually mean?

Swappiness is a 0–100 scale for how readily the kernel swaps memory pages to disk; the Ubuntu default is 60. Setting it to 10 tells the kernel to keep data in RAM as long as possible and use swap only when RAM is genuinely under pressure — the right bias for a server.

Does adding swap make my server faster?

No. Swap is slower than RAM by orders of magnitude, so it is a safety net, not a performance upgrade. If your server uses swap steadily under normal load, the right move is more RAM — either a bigger VPS plan or a managed setup that tracks memory for you.

Featured on Twelve Tools Hunt for Tools Featured on LaunchBuff Launch Llama Tools Launch your MCP Top Web Development Companies in the US - OnToplist.com Designer Listings Listed on SeeWhatNewAI