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.
- Create a 2 GiB file:
sudo fallocate -l 2G /swapfile - Make it readable by root only:
sudo chmod 600 /swapfile - Write the swap signature:
sudo mkswap /swapfile - Turn it on:
sudo swapon /swapfile - 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 -hIf 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 hibernation | Starting 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 GB | 2 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 GB | 4–8 GB | 4 GB |
| 16 GB (Quartz Q16, Chrono C16) | 4 GB | at least 4 GB | 4 GB |
| 32 GB (Chrono C32) | 8 GB (half of RAM, capped) | at least 4 GB | 4–8 GB |
| 64 GB (Chrono C64) | 8 GB (capped) | at least 4 GB | 4–8 GB |
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
ddthere, 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 /swapfileIf 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=progressdd 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 /swapfileSwapped-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 -hswapon --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/fstabThe 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 --showfindmnt –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 /swapfileAccording 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/swappinessTo try a lower value until the next reboot:
sudo sysctl vm.swappiness=10To 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.confWhich 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=0does 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, useswapoff.- You do not need to change
vm.vfs_cache_pressureto 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 /swapfileCreate 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 --showswapoff 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-reloadThe 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 10Read 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 | headVmSwap 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.
| Option | What it does | Needs a disk swap area? | Setup on Ubuntu 24.04 |
|---|---|---|---|
| Swap file | Moves idle pages to a file on disk | It is the disk swap area | The steps in this guide |
| zswap | Compresses 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 device | Yes | Kernel parameter zswap., or /sys/ while running |
| zram | Creates a compressed block device in RAM and uses it as swap | No | The systemd-zram-generator package (universe) plus a config file |
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/enabledN 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 --showIf /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 symptom | Cause | Fix |
|---|---|---|
swapon: /swapfile: insecure permissions 0644, 0600 suggested. | Other users can read the file | sudo 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 filesystem | Delete it and create it again with dd (step 2) |
swapon: /swapfile: swapon failed: Invalid argument | No swap signature (mkswap was skipped), or a copy-on-write file on Btrfs | Run sudo mkswap /swapfile; on Btrfs use btrfs filesystem mkswapfile |
swapon: /swapfile: swapon failed: Device or resource busy | The file is already in use as swap | Nothing to fix; confirm with swapon --show |
fallocate: fallocate failed: Text file busy | You tried to resize a swap file that is in use | Run sudo swapoff /swapfile first |
swapoff: /swapfile: swapoff failed: Cannot allocate memory | Free RAM cannot take back the swapped pages | Stop a memory-hungry service or turn on a temporary second swap file, then retry |
| Swap is gone after a reboot | The fstab line is missing or has a typo | Check grep swap /etc/ and sudo findmnt --verify, then redo step 5 |
Server is slow and si/so stay busy in vmstat 1 | The memory in active use is larger than RAM | Move to a plan with more RAM (next section) |
Processes are still killed with Out of memory | Swap filled up during the spike, or the spike is not short | Watch free -h during the spike; add swap only for short spikes, otherwise add RAM |
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.
| Plan | RAM | NVMe | Per hour | Monthly cap | Swap starting point |
|---|---|---|---|---|---|
| Quartz Q1 | 1 GB | 25 GB | $0.01/hour | $5.00/month cap | 1–2 GB |
| Quartz Q2 | 2 GB | 50 GB | $0.02/hour | $10.00/month cap | 2 GB |
| Quartz Q4 | 4 GB | 80 GB | $0.03/hour | $15.00/month cap | 2–4 GB |
| Quartz Q8 | 8 GB | 160 GB | $0.05/hour | $25.00/month cap | 4 GB |
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
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.



