By Alex Garnett and Vinayak Baranwal

When RAM fills up on Ubuntu servers, the Linux out-of-memory killer can terminate processes and disrupt services. Adding swap space gives the kernel secondary storage for anonymous memory pages so workloads can degrade gracefully instead of failing abruptly. This tutorial walks through creating a swapfile on Ubuntu 20.04 and Ubuntu 22.04, turning it on with mkswap and swapon, persisting it in /etc/fstab, tuning vm.swappiness and vm.vfs_cache_pressure, and fixing common setup errors. It is written for administrators managing Droplets, VPS instances, or bare metal running Ubuntu.
sudo swapon --show and free -h before making changes.fallocate on ext4, or with dd on Btrfs, XFS, or older filesystems where sparse allocation breaks swapon.chmod 600, initialize it with mkswap, and activate it with swapon./swapfile none swap sw 0 0 to /etc/fstab, then validate with sudo findmnt --verify --verbose before rebooting.vm.swappiness and vm.vfs_cache_pressure for server workloads, and store permanent values under /etc/sysctl.d/ on Ubuntu 22.04.swapoff, or remove the fstab entry and delete /swapfile to drop swap permanently.swapon invalid argument errors, permission problems, Btrfs fallocate issues, and fstab mistakes.sudo privileges. If you have not configured that yet, follow Initial Server Setup with Ubuntu 22.04./swapfile for a typical allocation (adjust upward if you choose a larger swapfile).On Ubuntu 20.04 and 22.04, the commands and sysctl paths in this guide behave the same. Many DigitalOcean and cloud images ship without active swap on smaller plans, while larger images may already include a swapfile or partition. Confirm what you have before adding another swap device.
To inspect current swap status from your server, run:
- sudo swapon --show
- free -h
total used free shared buff/cache available
Mem: 981Mi 122Mi 647Mi 0.0Ki 211Mi 714Mi
Swap: 0B 0B 0B
If sudo swapon --show prints nothing, no swap is active. The Swap line in free -h should read 0B for total swap in that case.
Swap is disk-backed space the kernel uses when it cannot keep all anonymous memory pages in RAM. Anonymous pages belong to heap and stack segments rather than file-backed mappings. When physical memory runs low, the kernel reclaims pages and may write cold anonymous pages to swap so active workloads keep RAM. 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.
If your server has already terminated a process due to memory exhaustion, swap would have bought the kernel time to reclaim pages before invoking the OOM killer. To check whether this has happened on your system, run sudo dmesg | grep -i 'killed process' or sudo journalctl -k | grep -i 'killed process' on Ubuntu 22.04. A match means RAM was exhausted, and adding swap reduces the chance of repeat terminations under similar load.
A swap partition is a dedicated disk slice formatted for swap. A swapfile is a regular file on an existing filesystem that the kernel uses as swap. Ubuntu installer defaults and many cloud images prefer swapfiles because resizing does not require repartitioning. Filesystem behavior matters: some layouts require dd instead of fallocate when creating the file. For background on how filesystems relate to storage layout, see How To Understand the Filesystem Layout in a Linux VPS.
| Feature | Swap Partition | Swapfile |
|---|---|---|
| Setup complexity | Requires partition alignment and often downtime to resize | Created with fallocate or dd, resized by replacing the file |
| Resize flexibility | Lower without repartitioning or LVM | Higher: replace file and rerun mkswap |
| Filesystem requirement | Own partition, no host filesystem | Lives on root or another mounted filesystem |
| Ubuntu default | Older installs and some images | Common on modern Ubuntu desktop and server installs |
| Hibernation support | Typically required for resume-to-disk | Not used for hibernate in typical server setups |
| Recommended for | Legacy disks, hibernate workflows | Droplets, VPS hosts, elastic sizing |
Size swap for your RAM tier and tolerance for disk-backed paging. The following ranges fit typical Linux server guidance:
| System RAM | Recommended Swap | Notes |
|---|---|---|
| Up to 2 GB | 2x RAM | Extra headroom on small instances |
| 2 to 8 GB | 2 to 4 GB | Typical VPS and web application hosts |
| 8 to 16 GB | 4 GB | Balanced paging reserve |
| 16 GB or more | 2 to 4 GB | Increase only if you need hibernate or unusual spikes |
The examples below use a 2 GB swapfile. Change the size arguments to match your plan.
- sudo swapon --show
When no swap devices are enabled, this command produces no lines and returns immediately. If swap is already configured, you see a table of devices.
NAME TYPE SIZE USED PRIO
/swapfile file 2G 0B -2
- free -h
total used free shared buff/cache available
Mem: 981Mi 122Mi 647Mi 0.0Ki 211Mi 714Mi
Swap: 0B 0B 0B
When swap is active, the Swap row shows nonzero totals.
- df -h
Filesystem Size Used Avail Use% Mounted on
udev 474M 0 474M 0% /dev
tmpfs 99M 932K 98M 1% /run
/dev/vda1 25G 1.4G 23G 7% /
tmpfs 491M 0 491M 0% /dev/shm
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 491M 0 491M 0% /sys/fs/cgroup
/dev/vda15 105M 3.9M 101M 4% /boot/efi
/dev/loop0 55M 55M 0 100% /snap/core18/1705
/dev/loop1 69M 69M 0 100% /snap/lxd/14804
/dev/loop2 28M 28M 0 100% /snap/snapd/7264
tmpfs 99M 0 99M 0% /run/user/1000
Confirm the mount point that will hold /swapfile, usually /, has enough free space for the swapfile plus normal growth.
fallocate reserves space quickly on filesystems that write fully allocated extents suitable for swap.
- sudo fallocate -l 2G /swapfile
- ls -lh /swapfile
-rw-r--r-- 1 root root 2.0G Apr 25 11:14 /swapfile
Pick a size from the table in the previous section instead of copying the example blindly.
On Btrfs, fallocate creates files with unwritten extents, which causes swapon to fail. Use the dd method on Btrfs filesystems.
dd writes zero-filled blocks and produces a fully contiguous file that passes the kernel’s swap header checks.
- sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
2048+0 records in
2048+0 records out
2147483648 bytes (2.1 GB, 2.0 GiB) copied, 3.12345 s, 687 MB/s
The command takes longer than fallocate but produces a fully allocated file without holes.
| Factor | fallocate | dd |
|---|---|---|
| Speed | Fast reservation | Slower full write |
| Filesystem compatibility | Works on ext4 and others that fully allocate | Works broadly when /dev/zero writes succeed |
| Sparse file risk | Possible on CoW or delayed allocation setups | Low: contiguous writes fill the file |
| Btrfs support | Not suitable for swapfiles | Use dd instead |
| XFS support | Often problematic for swap; prefer dd |
Preferred |
| Recommended for | ext4 roots on Droplets | Btrfs, XFS, or when swapon rejects a fallocated file |
Swapfiles can contain remnants of process memory, including credentials or session material. World-readable swap is an information disclosure risk.
- sudo chmod 600 /swapfile
- ls -lh /swapfile
-rw------- 1 root root 2.0G Apr 25 11:14 /swapfile
Only the root user should retain read and write bits.
mkswap writes the swap header, assigns a UUID, and optionally a label.
- sudo mkswap /swapfile
Setting up swapspace version 1, size = 2 GiB (2147483648 bytes)
no label, UUID=6e965805-2ab9-450f-aed6-577e74089dbf
- sudo swapon /swapfile
- sudo swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 2G 0B -2
The PRIO column shows the swap priority. The kernel auto-assigns negative priorities (-2, -3, and so on) to swap devices that are added without an explicit priority. Higher values are used first, so a single swapfile at -2 is fine. If you add a second swap device on faster storage and want the kernel to prefer it, set a higher priority with swapon -p 10 /path/to/faster-swap or by appending pri=10 to the fstab options field.
- free -h
total used free shared buff/cache available
Mem: 981Mi 123Mi 644Mi 0.0Ki 213Mi 714Mi
Swap: 2.0Gi 0B 2.0Gi
The kernel begins paging to /swapfile when memory pressure warrants it.
Changes so far apply until reboot. Add an /etc/fstab entry so systemd mounts swap automatically.
Back up fstab before editing:
- sudo cp /etc/fstab /etc/fstab.bak
Append the swap line:
- echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
The five fields in this entry tell systemd how to mount the swapfile at boot. /swapfile is the device or file path. none is the mount point, which is unused for swap because swap is not mounted into the filesystem tree. swap is the filesystem type. sw is the mount option set, which for swap means default behavior. The first 0 disables dump backup for this entry. The second 0 sets the fsck pass order to skip filesystem checks, which is correct for swap.
Validate syntax and mount targets:
- sudo findmnt --verify --verbose
/
[ ] target exists
[ ] UUID=b3e62c74-e07b-4b57-bfb8-b39bbdbda993
[ ] LABEL: (none)
[ ] FS options: rw,relatime
/swapfile
[ ] target exists
0 parse errors, 0 errors, 0 warnings
A malformed /etc/fstab entry can prevent the system from booting. Always back up the file first and validate with sudo findmnt --verify before rebooting.
For more on /etc/fstab, mounting, and storage administration, read How To Perform Basic Administration Tasks for Storage Devices in Linux.
Kernel tuning changes how eagerly Ubuntu moves pages to swap and how long inode and dentry caches stay warm. Watch RSS and swap usage with tools described in How To Use Top, Netstat, Du, & Other Tools to Monitor Server Resources after you adjust these settings.
- cat /proc/sys/vm/swappiness
60
- sudo sysctl vm.swappiness=10
vm.swappiness = 10
| Value | Behavior | Use Case |
|---|---|---|
| 0 | Swap only under heavy pressure | Extreme latency-sensitive workloads |
| 1 | Near-zero swap tendency | MySQL, PostgreSQL |
| 10 | Low swap preference | General Ubuntu servers, VPS hosts, Droplets |
| 60 | Kernel default | Desktop-oriented mixes |
| 100 | Aggressive swapping | Rarely appropriate on servers |
- cat /proc/sys/vm/vfs_cache_pressure
100
- sudo sysctl vm.vfs_cache_pressure=50
vm.vfs_cache_pressure = 50
This parameter scales how aggressively the kernel shrinks inode and dentry caches versus page cache; lowering it keeps filesystem metadata cached longer under memory pressure.
Ubuntu 22.04 recommends drop-in files under /etc/sysctl.d/ instead of editing monolithic configs. Choose one of the following approaches. Do not run both, since duplicate definitions across files create configuration drift.
Modern (recommended):
- echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swap.conf
- echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.d/99-swap.conf
Legacy compatible:
- echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
- echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
Reload settings without rebooting:
- sudo sysctl --system
* Applying /etc/sysctl.d/99-swap.conf ...
vm.swappiness = 10
vm.vfs_cache_pressure = 50
Temporarily stop using the swapfile without deleting it:
- sudo swapoff /swapfile
- sudo swapon --show
When no swap devices are active, sudo swapon --show prints nothing and returns to the prompt.
An empty result confirms swap is inactive.
Disabling swap while applications are under memory pressure can trigger OOM kills. Verify free memory with free -h before running swapoff.
To remove swap permanently, delete the /swapfile line from /etc/fstab, run sudo swapoff /swapfile if it is active, then delete the file:
- sudo rm /swapfile
- free -h
Confirm the Swap totals return to zero after removal.
| Error | Cause | Fix |
|---|---|---|
swapon: /swapfile: Invalid argument |
mkswap missing, or sparse fallocated file (common on Btrfs) |
Run sudo mkswap /swapfile, or recreate the file with dd on Btrfs |
chmod: cannot access '/swapfile': No such file |
File creation failed silently | Check df -h for space, rerun fallocate or dd |
swapon: /swapfile: swapon failed: Operation not permitted |
Permissions too open | Run sudo chmod 600 /swapfile before mkswap |
| Swap not active after reboot | /etc/fstab missing or malformed line |
Run sudo findmnt --verify --verbose, ensure /swapfile none swap sw 0 0 |
fallocate failed on Btrfs |
Btrfs cannot provision swap via fallocate safely |
Delete the incomplete file with sudo rm /swapfile, then recreate with dd |
Run sudo mkswap /swapfile if you skipped initialization. If the error persists, check whether the root filesystem is Btrfs or another CoW filesystem:
- findmnt -no FSTYPE /
If the result is btrfs, remove the bad file and recreate it with dd, then repeat chmod, mkswap, and swapon:
- sudo swapoff /swapfile
- sudo rm /swapfile
- sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
Confirm the fstab line matches exactly:
- grep swapfile /etc/fstab
/swapfile none swap sw 0 0
Run sudo findmnt --verify --verbose and fix reported issues before rebooting again.
If the fstab entry is correct but the file no longer exists on disk, recreate it by following Step 2, then rerun chmod 600, mkswap, and swapon. This often happens after a resize where /swapfile was deleted but fstab was not updated to a new path. Confirm the file exists with ls -lh /swapfile before rebooting.
Ensure you used sudo with fallocate or dd. If creation succeeds but swapon reports permission errors, reset ownership and mode:
- sudo chown root:root /swapfile
- sudo chmod 600 /swapfile
Use dd to allocate the swapfile. If the swapfile lives on a Btrfs subvolume with copy-on-write enabled, also disable CoW on the empty file before writing data into it. Skip the truncate and chattr +C steps if your swapfile is on ext4 or XFS.
- sudo truncate -s 0 /swapfile
- sudo chattr +C /swapfile
- sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
Then continue with chmod, mkswap, swapon, and fstab as before.
Match roughly twice RAM when RAM is 2 GB or below. For 2 to 8 GB RAM, allocate 2 to 4 GB swap. Between 8 and 16 GB RAM, about 4 GB swap fits many workloads. Above 16 GB RAM, 2 to 4 GB swap is typical unless you need hibernation.
A swap partition is a dedicated slice of disk formatted as swap. A swapfile is a normal file on your filesystem that the kernel treats as swap. Swapfiles are flexible and align with modern Ubuntu defaults because they avoid repartitioning when resizing.
Btrfs does not guarantee fully allocated extents when you fallocate a swapfile, so swapon may reject the file. Writing with dd from /dev/zero fills every block and satisfies the kernel checks.
Run sudo swapon --show for device-level detail and free -h for aggregate totals. Both commands reflect active swap only after swapon succeeds.
10 is a practical starting point for Droplet workloads that prefer RAM over paging. Databases that stall on swap reads often use 1. Keep 60 only when desktop-like mixing warrants more paging.
Add /swapfile none swap sw 0 0 to /etc/fstab, validate with sudo findmnt --verify, then reboot when convenient. Without that line, Ubuntu will not enable the swapfile automatically.
Yes. Create the swapfile, lock permissions, run mkswap, enable with swapon, and persist via /etc/fstab. No reinstall is required.
To resize an existing swapfile from 2 GB to 4 GB on ext4, disable the active swap, replace the file, and re-enable. The fstab entry stays the same as long as the path does not change.
- sudo swapoff /swapfile
- sudo rm /swapfile
- sudo fallocate -l 4G /swapfile
- sudo chmod 600 /swapfile
- sudo mkswap /swapfile
- sudo swapon /swapfile
Verify the new size with sudo swapon --show:
- sudo swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 4G 0B -2
If the system is under memory pressure, run free -h before swapoff to confirm enough RAM is available. Disabling a 2 GB swap that is currently 1.5 GB used will force those pages back into RAM and may trigger OOM kills on a tight server.
This article explained how to add swap on Ubuntu 20.04 and Ubuntu 22.04 using a swapfile: checking existing memory and disk headroom, choosing between fallocate and dd, locking down permissions, initializing swap with mkswap, enabling it with swapon, and persisting configuration through /etc/fstab with findmnt validation. It also covered tuning vm.swappiness and vm.vfs_cache_pressure via /etc/sysctl.d/99-swap.conf, safely disabling swap, and troubleshooting typical swapon and fstab failures.
You can now provision swap when sizing a new Droplet, extend paging capacity on an existing server that spikes RAM usage, and recover quickly when permission or filesystem quirks block activation. Treat swap as a buffer while you right-size applications or plan hardware upgrades.
Continue hardening storage semantics with How To Perform Basic Administration Tasks for Storage Devices in Linux and How To Understand the Filesystem Layout in a Linux VPS. Monitor paging behavior using How To Use Top, Netstat, Du, & Other Tools to Monitor Server Resources. If you still need baseline SSH and firewall setup, repeat Initial Server Setup with Ubuntu 22.04 on fresh instances before layering swap changes.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Former Senior DevOps Technical Writer at DigitalOcean. Expertise in topics including Ubuntu 22.04, Linux, Rocky Linux, Debian 11, and more.
Building future-ready infrastructure with Linux, Cloud, and DevOps. Full Stack Developer & System Administrator. Technical Writer @ DigitalOcean | GitHub Contributor | Passionate about Docker, PostgreSQL, and Open Source | Exploring NLP & AI-TensorFlow | Nailed over 50+ deployments across production environments.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
I don’t want to sound like a cock but… WTF? My first python game in school had less lines of code than this! Why are trivial stuff like this still a pain in the ass on Linux? Seriously!? Don’t get me wrong, thanks for the tutorial, but… WHY?
Note that fallocate doesn’t work to create a file for use by swap because it leaves “holes” in the file. You have to use dd.
What an amazing article, thanks a lot. Very helpful and easy to follow.
Most highly helpful. Also applies to 24.x when rebuilding from a hosed 22.04 build.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.