How to Add Swap on Ubuntu 24.04: Swap File, Size and Swappiness

Add a swap file to an Ubuntu 24.04 VPS in five commands, size it with Ubuntu’s own installer formula, tune swappiness, resize or remove it, and fix the errors swapon prints.

Title card reading “Add swap on Ubuntu 24.04” for the HourlyVPS guide to adding a swap file on an Ubuntu 24.04 VPS

To add swap on Ubuntu 24.04, create a swap file with fallocate, make it readable by root only with chmod 600, format it with mkswap, turn it on with swapon, and add one line to /etc/fstab so it comes back after a reboot. You do not need to repartition or reboot, and 2 GB of swap is a sound starting size on a VPS with 1 or 2 GB of RAM.

Swap gives the kernel somewhere to park memory pages that nothing is using, so a short memory spike slows the server down instead of ending with the out-of-memory killer. Swap is not extra RAM. This guide sizes swap for each VPS plan from Ubuntu’s own installer formula, explains every command and its check, and covers swappiness, resizing, removal, zram, zswap and the errors swapon actually prints.

Key takeaways

  • To add swap on Ubuntu 24.04, run sudo fallocate -l 2G /swapfile, chmod 600, mkswap and swapon, then add “/swapfile none swap sw 0 0” to /etc/fstab; no reboot is needed.
  • Ubuntu’s own installer sizes swap at about 2 GB for 1–2 GB of RAM, the RAM size up to 4 GB, 4 GB up to 16 GB, and never more than 8 GB; on a VPS, 1–4 GB covers most plans.
  • Use fallocate on ext4 and dd elsewhere, because swapon rejects swap files with holes; on Btrfs, use btrfs filesystem mkswapfile.
  • vm.swappiness runs from 0 to 200 with a default of 60; 0 does not turn swap off, and a lasting change belongs in /etc/sysctl.d/.
  • Steady si and so values in vmstat 1 mean the server is short of RAM, not swap: move up a plan instead of growing the swap file.

Add swap on Ubuntu 24.04 in five commands

Log in as your sudo user (see how to connect to a VPS with SSH) on a server you have already locked down with the VPS security checklist. Then run these five commands in order. The sections below explain each one and show how to check it.

  1. Create a 2 GiB file: sudo fallocate -l 2G /swapfile
  2. Make it readable by root only: sudo chmod 600 /swapfile
  3. Write the swap signature: sudo mkswap /swapfile
  4. Turn it on: sudo swapon /swapfile
  5. Keep it after reboots: echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Then run swapon --show. If it lists /swapfile with type file and size 2G, swap is live. The fstab line uses the same fields that Ubuntu’s server installer writes for its own swap file, /swap.img (curtin swap.py).

Does your VPS need swap?

Check first. VPS images often boot with no swap at all, and on a small plan that leaves the kernel one option when memory runs out.

sudo swapon --show
free -h

If swapon --show prints nothing, the server has no swap, and the Swap: row of free -h shows 0B. Watch the available column: the free(1) manual defines it as an estimate of the memory available for starting new applications without swapping.

Without swap, the kernel frees memory mainly by dropping file cache, because memory that programs allocated has nowhere else to go. When dropping cache is not enough, the out-of-memory (OOM) killer ends a process and logs it. To find kills since the last boot:

sudo journalctl -k | grep -i "killed process"

A line that starts with Out of memory: Killed process, followed by a process ID and a program name, means the server has already run out of memory once since it booted.

  • Add swap on 1 GB and 2 GB plans that run a database next to an app, for package installs and builds that spike memory for a few minutes (see how much RAM Coolify builds need), and for tools that ask for it. YABS, for example, tells you to add at least 1 GB of swap when Geekbench fails on a low-memory server (see the VPS benchmark guide).
  • Swap will not rescue a workload that needs more memory than the server has, all the time. If a model or a database cache is larger than RAM, swap turns every access into disk I/O. Size RAM for it instead, as in how much RAM Ollama needs.
  • Turn swap off on a load generator. The k6 load-testing guide explains why k6’s docs recommend it: a load generator that swaps produces results you cannot trust.

How much swap does a VPS need?

Size swap as a buffer for spikes, not as memory you plan to use. The old “twice the RAM” rule does not scale: Red Hat’s RHEL 9 table asks for twice the RAM only below 2 GB, the RAM size up to 8 GB, and at least 4 GB above that. Its larger figures, up to 3 times the RAM, are for hibernation, which a server you reach over SSH does not use.

Curtin, the tool behind Ubuntu’s server installer, sizes its default /swap.img by RAM. For up to 1 GB of RAM it uses double the RAM, up to 2 GB a flat 2 GB, up to 4 GB the same as RAM, up to 16 GB a flat 4 GB, and up to 64 GB half the RAM. The result is capped at 8 GB or a quarter of the free disk space, whichever is smaller (suggested_swapsize()). Red Hat’s recommendation lands close to it:

RAM (HourlyVPS plans)Ubuntu installer (curtin)Red Hat RHEL 9, no hibernationStarting point on a VPS
1 GB (Quartz Q1)about 2 GB (2 × RAM)2 GB (2 × RAM)1–2 GB
2 GB (Quartz Q2)2 GB2 GB (equal to RAM)2 GB
4 GB (Quartz Q4)about 4 GB (equal to RAM)4 GB (equal to RAM)2–4 GB
8 GB (Quartz Q8, Chrono C8)4 GB4–8 GB4 GB
16 GB (Quartz Q16, Chrono C16)4 GBat least 4 GB4 GB
32 GB (Chrono C32)8 GB (half of RAM, capped)at least 4 GB4–8 GB
64 GB (Chrono C64)8 GB (capped)at least 4 GB4–8 GB
Swap size by RAM. Installer values follow curtin’s formula on a disk with room to spare. Red Hat values come from “Recommended system swap space” in the RHEL 9 docs; 8 GB sits on the boundary between two of its rows. The last column is this guide’s reasoning, not a rule.

The last column stops at 4 GB for most plans for a simple reason. Swap on a VPS lives on the same NVMe disk as your data, so every gigabyte of swap is a gigabyte of disk. On a Quartz Q1 with 25 GB of NVMe, 2 GB of swap takes 8% of the disk. A server that needs more than a few gigabytes of swap all the time needs more RAM, and a bigger swap file will not change that.

Disk speed sets how much swapping hurts. The kernel documentation notes that swap produces random I/O, which is less efficient than the way files are read back. To put a number on your server’s random reads and writes, run the fio disk test.

Tip: If swapon --show already lists /swap.img, the server most likely came from Ubuntu’s installer and already has swap. Resize that file with the steps further down instead of adding a second one. Two files also work: mkswap(8) notes that Linux allows 32 swap areas.

Step by step: create, enable and keep a swap file

Step 1: Check the filesystem and free space

df -hT /

The Type column decides how to create the file, and Avail shows how much room you have. The kernel writes to a swap file’s disk blocks directly, without the filesystem’s help, so the file must have no holes. The swapon(8) manual warns that cp and truncate create files with holes and that fallocate may too, depending on the filesystem.

  • ext4: use fallocate. Ubuntu’s installer does the same, and Red Hat calls it preferable on ext4 and XFS because it is faster than writing zeros.
  • XFS: swapon(8) says preallocated swap files work on XFS since Linux 4.18. Ubuntu’s installer still uses dd there, and so can you.
  • Btrfs: run sudo btrfs filesystem mkswapfile --size 2G /swapfile (btrfs-progs 6.1 or later; Ubuntu 24.04 ships 6.6), then continue at step 4. The Btrfs documentation lists the limits. For example, a subvolume with an active swap file cannot be snapshotted.

Step 2: Create the swap file

On ext4, allocate the file in one call. Replace 2G with the size you picked; fallocate(1) reads the suffix G as GiB.

sudo fallocate -l 2G /swapfile

If fallocate fails, or the filesystem is not ext4, write zeros with dd instead. swapon(8) calls this the most portable method. count is the size in MiB, so 2048 makes 2 GiB:

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

dd writes every byte, so it takes longer than fallocate and keeps the disk busy while it runs.

Step 3: Lock it down and format it

sudo chmod 600 /swapfile
sudo mkswap /swapfile

Swapped-out pages can hold anything a program had in memory, passwords and keys included, so only root should be able to read the file. If you skip chmod, swapon still turns the file on, but it prints a warning that the permissions are insecure and suggests 0600. mkswap writes the swap header, then prints the size and a new UUID.

Step 4: Turn it on and check

sudo swapon /swapfile
swapon --show
free -h

swapon --show should list /swapfile with type file, the size you chose, little or nothing in the USED column and a negative priority. Linux assigns falling negative priorities to swap areas that were not given one. The Swap: row of free -h now shows the new total.

Step 5: Make it permanent in /etc/fstab

Swap that you turn on with swapon stays on only until the next reboot. To keep it, add a line to /etc/fstab. Back up the file first. The grep check stops a second run from adding a duplicate line:

sudo cp /etc/fstab /etc/fstab.bak
grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

The six fields are the file, the mount point, the type swap, the options, and two zeros for the dump and fsck order. For swap, fstab(5) says the mount point should be none.

Then prove the line works without rebooting. systemd builds its swap units from fstab, so reload it, check the file, and let swapon -a turn swap back on from fstab alone:

sudo systemctl daemon-reload
sudo findmnt --verify
sudo swapoff /swapfile
sudo swapon -a
swapon --show

findmnt –verify prints Success, no errors or warnings detected when the file is clean. Without the daemon-reload, it warns that systemd still uses the old version of fstab. If /swapfile appears in the output of the last command, the fstab line works.

Warning: A broken /etc/fstab is a classic way to turn a routine reboot into a console session. Keep /etc/fstab.bak until the server has rebooted cleanly once, and know where the VNC console is. The lockout recovery steps use the same console, and from it you can copy the backup back into place.

Ubuntu 26.04 and Debian: what changes

On Debian 12 the commands are identical (util-linux 2.38.1). On Ubuntu 26.04 LTS and Debian 13 (util-linux 2.41), one command replaces steps 2 and 3:

sudo mkswap --size 2G --file /swapfile

According to mkswap(8) on Ubuntu 26.04, --file creates the swap file “with the appropriate file permissions and populated blocks on disk”. Since util-linux 2.41 it also sets the no-copy-on-write attribute that Btrfs needs. Ubuntu 24.04 ships util-linux 2.39.3, which has no --file option.

How do you change swappiness on Ubuntu 24.04?

vm.swappiness tells the kernel how expensive swap I/O is compared with reading files back from disk. The kernel documentation defines it as a value from 0 to 200, with a default of 60. At 100 the kernel treats both kinds of I/O as equally costly. Lower values make it prefer dropping file cache over swapping out program memory. Check the current value:

cat /proc/sys/vm/swappiness

To try a lower value until the next reboot:

sudo sysctl vm.swappiness=10

To keep the setting, put it in a drop-in file. sysctl.d(5) says files in /etc/sysctl.d/ are applied early at every boot:

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

Which value should you use? Start with the default of 60. The kernel docs say the right value “will require experimentation and will also be workload-dependent”. Many server admins choose 10 so that idle program memory stays in RAM longer. That is a preference, not a documented recommendation, so compare vmstat output before and after. Two misunderstandings are worth avoiding:

  • vm.swappiness=0 does not turn swap off. The kernel docs say that at 0 the kernel does not start swapping until free and file-backed pages fall below a zone’s high watermark. To turn swap off, use swapoff.
  • You do not need to change vm.vfs_cache_pressure to use swap. The same page warns that setting it to 0 “can easily lead to out-of-memory conditions”.

How do you resize or remove a swap file?

You cannot resize a swap file while it is in use: the kernel refuses with fallocate failed: Text file busy. Turn it off, recreate it at the new size, and turn it back on. The fstab line refers to the path, so it stays as it is.

Resize the swap file

Turn the old file off and delete it:

sudo swapoff /swapfile
sudo rm /swapfile

Create it again at the new size, here 4 GiB, and turn it on:

sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
swapon --show

swapoff must first move every swapped page back into RAM or into another swap area. If there is not enough room, it fails with Cannot allocate memory. To avoid that, create and turn on a temporary second file, such as /swapfile2, before you turn the first one off. Remove the temporary file the same way when you are done.

Remove swap completely

sudo swapoff /swapfile
sudo cp /etc/fstab /etc/fstab.bak
sudo sed -i '\|^/swapfile |d' /etc/fstab
sudo rm /swapfile
sudo systemctl daemon-reload

The sed command deletes the fstab line that starts with /swapfile followed by a space. If you wrote the line with tabs, delete it in an editor instead. Afterwards swapon --show prints nothing.

Is swap helping or hurting? How to read the numbers

Swap in use is not a problem by itself. The kernel moves out pages that have not been touched for a while, and swap that is used but quiet costs nothing. What matters is traffic in and out of swap, which vmstat shows once a second:

vmstat 1 10

Read the si and so columns: memory swapped in from disk and swapped out to disk per second. Zeros with occasional bursts mean swap is doing its job as a buffer. Steady non-zero values in both columns while your app is slow mean the memory it actively uses does not fit in RAM. The server is thrashing, and the fix is more RAM, not more swap.

To see which programs have pages in swap, largest first:

awk '/^Name:/{n=$NF} /^VmSwap:/{if ($(NF-1)>0) print $(NF-1), "kB", n}' /proc/[0-9]*/status 2>/dev/null | sort -rn | head

VmSwap is the swapped-out part of a process’s private memory, and proc_pid_status(5) warns that the figure is approximate. If the program you care about tops this list while si and so are busy, it needs more RAM. Databases are the usual case: size their caches to fit in RAM, as in the PostgreSQL tuning table for each VPS size and the WordPress sizing guide.

Swap file, zswap or zram?

zswap and zram both compress memory in RAM, either before it reaches the disk or instead of the disk. They trade CPU time for fewer disk writes.

OptionWhat it doesNeeds a disk swap area?Setup on Ubuntu 24.04
Swap fileMoves idle pages to a file on diskIt is the disk swap areaThe steps in this guide
zswapCompresses pages on their way to swap and keeps them in a RAM pool; when the pool is full, it moves pages on to the swap deviceYesKernel parameter zswap.enabled=1, or /sys/module/zswap/parameters/enabled while running
zramCreates a compressed block device in RAM and uses it as swapNoThe systemd-zram-generator package (universe) plus a config file
Sources: the Linux kernel zswap and zram documentation, and the zram-generator README.

zswap is the smaller change, because it sits in front of the swap file you just made. Check whether it is on, then turn it on until the next reboot:

cat /sys/module/zswap/parameters/enabled
echo 1 | sudo tee /sys/module/zswap/parameters/enabled

N means zswap is off. Whether it starts on depends on how the kernel was built (the CONFIG_ZSWAP_DEFAULT_ON option). The kernel zswap docs say to make it permanent by adding zswap.enabled=1 to the kernel command line.

zram replaces disk swap with RAM. The kernel zram docs expect about a 2:1 compression ratio, so zram makes the most sense when memory compresses well and the disk is the bottleneck. The zram-generator README sets it up with one config file and two systemctl commands:

sudo apt install systemd-zram-generator
printf '[zram0]\nzram-size = ram / 2\n' | sudo tee /etc/systemd/zram-generator.conf
sudo systemctl daemon-reload
sudo systemctl start /dev/zram0
swapon --show

If /dev/zram0 never appears, your image’s kernel may not include the zram module. sudo modprobe zram tells you; if it fails, stay with a swap file. On a 1 GB plan, keep the swap file as your base in any case, because zram stores its compressed pages in the same RAM you are short of.

Swap errors on Ubuntu and how to fix them

Message or symptomCauseFix
swapon: /swapfile: insecure permissions 0644, 0600 suggested.Other users can read the filesudo chmod 600 /swapfile. Swap still turned on; this is a warning
swapon: /swapfile: skipping - it appears to have holes.The file was made with truncate or cp, or fallocate left holes on this filesystemDelete it and create it again with dd (step 2)
swapon: /swapfile: swapon failed: Invalid argumentNo swap signature (mkswap was skipped), or a copy-on-write file on BtrfsRun sudo mkswap /swapfile; on Btrfs use btrfs filesystem mkswapfile
swapon: /swapfile: swapon failed: Device or resource busyThe file is already in use as swapNothing to fix; confirm with swapon --show
fallocate: fallocate failed: Text file busyYou tried to resize a swap file that is in useRun sudo swapoff /swapfile first
swapoff: /swapfile: swapoff failed: Cannot allocate memoryFree RAM cannot take back the swapped pagesStop a memory-hungry service or turn on a temporary second swap file, then retry
Swap is gone after a rebootThe fstab line is missing or has a typoCheck grep swap /etc/fstab and sudo findmnt --verify, then redo step 5
Server is slow and si/so stay busy in vmstat 1The memory in active use is larger than RAMMove to a plan with more RAM (next section)
Processes are still killed with Out of memorySwap filled up during the spike, or the spike is not shortWatch free -h during the spike; add swap only for short spikes, otherwise add RAM
Message texts as printed by util-linux 2.39.3 on Ubuntu 24.04 and by the Linux kernel’s OOM killer.

What does swap cost on a VPS, and when should you buy RAM instead?

Swap costs nothing extra. It is space on the NVMe disk that comes with the plan. RAM is what you pay for, so the real decision is when to stop relying on swap and move up a size.

PlanRAMNVMePer hourMonthly capSwap starting point
Quartz Q11 GB25 GB$0.01/hour$5.00/month cap1–2 GB
Quartz Q22 GB50 GB$0.02/hour$10.00/month cap2 GB
Quartz Q44 GB80 GB$0.03/hour$15.00/month cap2–4 GB
Quartz Q88 GB160 GB$0.05/hour$25.00/month cap4 GB
Each server is billed by the hour; the monthly cap is the most it is charged in a billing period, after which its charges stop until the next one.

Practicing this guide on a Quartz Q1 for an hour costs $0.01. Billing is by the hour: every hour a server exists is charged at the plan’s hourly rate. The price tapes and cost tables on this site count every started hour as a full hour, so they show the most a duration can cost; the cost calculator charges a partial hour to the nearest cent, as the bill does. Delete the server when you finish. A stopped server is still billed, because its vCPU, memory, disk and IP addresses stay reserved for you; only deleting the server stops billing. The Linux labs on a VPS use the same throwaway-server approach for other skills.

Billing: Each new server is ordered with an initial credit, prepaid and used for that server’s hours; the hourly billing guide walks through it with examples. A server you keep is billed by the hour and never costs more than the plan’s monthly price in a billing period (one month from your order date). That is how a monthly VPS works here: no contract and no plan to switch to.

If vmstat shows steady swapping, deploy the next plan up, move the workload, and delete the old server after the delete-a-VPS checklist. Compare every plan’s hourly price and monthly cap on the pricing page.

Deploy this setup

Deploy a 1 GB Ubuntu 24.04 server and add swap

Quartz Q1 · 1 shared vCPU · 1 GB RAM · 25 GB NVMe · Istanbul

  • Per hour$0.01/hourFor this job
  • Per day (24 h)$0.24/day
  • Monthly cap$5.00/month
Deploy Quartz Q1

Starts with a $5 initial credit, which goes into the server’s balance and pays for its hours.

Billed by the hour, never more than $5.00 per billing period. Delete the server and billing stops.

FAQ

Does an Ubuntu 24.04 VPS need swap?

It is not required, but on plans with 1 to 4 GB of RAM a small swap file is cheap insurance. Without it, a memory spike ends with the kernel’s OOM killer stopping a process. Run swapon --show to check, because many VPS images ship with no swap.

How much swap do I need for 1 GB of RAM?

Ubuntu’s installer would create about 2 GB, and Red Hat recommends twice the RAM below 2 GB. On a 1 GB VPS with a 25 GB disk, 1 to 2 GB is a sensible start.

Should I use a swap file or a swap partition on a VPS?

A swap file. Ubuntu’s own server installer creates /swap.img instead of a partition, and you can resize a file without repartitioning the VPS disk. It must be allocated without holes, which is why you use fallocate on ext4 or dd.

What swappiness should a server use?

The kernel default is 60 on a scale of 0 to 200, and the kernel docs say the right value depends on the workload. Many admins use 10 on servers to keep program memory in RAM longer; set it in /etc/sysctl.d/ and compare vmstat before and after.

Can I add swap without rebooting?

Yes. swapon turns a new swap file on immediately, and the /etc/fstab line only matters at the next boot. To test that line without rebooting, run sudo swapoff /swapfile and then sudo swapon -a.

Why is swap used when RAM is free?

The kernel moves pages that have not been used for a while to swap so the RAM can serve as file cache, and vm.swappiness sets how eagerly it does so. Used swap is harmless while the si and so columns in vmstat stay near zero.

Does adding swap make a VPS faster?

No. Swap lives on disk, which is far slower than RAM, so it prevents crashes during short spikes rather than adding speed. If the server swaps constantly, it needs more RAM.

Sources

  1. swapon(8): enable/disable devices and files for paging and swapping (util-linux 2.39.3)Ubuntu Manpages, Ubuntu 24.04 LTS · manpages.ubuntu.com · checked
  2. mkswap(8): set up a Linux swap area (util-linux 2.39.3)Ubuntu Manpages, Ubuntu 24.04 LTS · manpages.ubuntu.com · checked
  3. mkswap(8) with --file and --size (util-linux 2.41.3)Ubuntu Manpages, Ubuntu 26.04 LTS · manpages.ubuntu.com · checked
  4. Documentation for /proc/sys/vm/: swappiness and vfs_cache_pressureThe Linux Kernel documentation · docs.kernel.org · checked
  5. curtin/swap.py: suggested_swapsize() and setup_swapfile()Canonical (Ubuntu server installer) · github.com · checked
  6. Getting started with swap: recommended system swap space and creating a swap file (RHEL 9)Red Hat Documentation · docs.redhat.com · checked
  7. zswapThe Linux Kernel documentation · docs.kernel.org · checked
  8. zram: compressed RAM-based block devicesThe Linux Kernel documentation · docs.kernel.org · checked
  9. zram-generator: systemd unit generator for zram devices (README)systemd project on GitHub · github.com · checked
  10. SwapfileBTRFS documentation · btrfs.readthedocs.io · checked
All posts