How to Add Swap Space on Ubuntu 20.04 and Ubuntu 22.04

When an Ubuntu server runs out of RAM, the Linux out-of-memory killer may stop processes and interrupt running services. Swap space provides the kernel with additional disk-backed storage for anonymous memory pages, allowing workloads to slow down more gracefully instead of failing immediately. This guide explains how to create a swapfile on Ubuntu 20.04 and Ubuntu 22.04, initialize and enable it with mkswap and swapon, make the configuration persistent through /etc/fstab, adjust vm.swappiness and vm.vfs_cache_pressure, and resolve common swap configuration problems. The instructions apply to administrators working with cloud servers, VPS systems, virtual machines, or bare-metal Ubuntu installations.

Key Points for Configuring Swap on Ubuntu

  • Check whether swap already exists with sudo swapon --show and free -h before changing the system.
  • Create the swapfile with fallocate on ext4, or use dd on Btrfs, XFS, and older filesystems where sparse allocation can prevent swapon from working.
  • Protect the swapfile with chmod 600, prepare it using mkswap, and activate it with swapon.
  • Make swap survive reboots by adding /swapfile none swap sw 0 0 to /etc/fstab, then check the configuration with sudo findmnt --verify --verbose before restarting.
  • Adjust vm.swappiness and vm.vfs_cache_pressure for server workloads, and save permanent settings in /etc/sysctl.d/ on Ubuntu 22.04.
  • Turn swap off temporarily with swapoff, or permanently remove it by deleting its fstab entry and the /swapfile file.
  • Resolve frequent problems including swapon invalid argument messages, permission errors, Btrfs fallocate failures, and incorrect fstab configuration.

Prerequisites for Adding Swap Space

  • An Ubuntu 20.04 or Ubuntu 22.04 server with a non-root account that has sudo privileges. Configure a non-root administrative user first if one is not already available.
  • At least 2 GB of unused disk capacity on the filesystem where /swapfile will be stored for the example allocation. More free space is required if you choose a larger swapfile.
  • Basic familiarity with terminal commands and Linux file permissions.

The commands and sysctl locations described here work in the same way on Ubuntu 20.04 and Ubuntu 22.04. Some cloud and VPS images do not include active swap on smaller server configurations, while other installations may already have a swapfile or swap partition. Check the current configuration before creating an additional swap device.

To view the current swap configuration, run:



              total        used        free      shared  buff/cache   available
Mem:          981Mi       122Mi       647Mi       0.0Ki       211Mi       714Mi
Swap:            0B          0B          0B

If sudo swapon --show returns no output, the system currently has no active swap. In that situation, the Swap row displayed by free -h should report a total value of 0B.

What Swap Space Is and When a Linux Server Needs It

How the Linux Kernel Uses Swap Space

Swap is storage-backed space that Linux can use when all anonymous memory pages cannot remain in physical RAM. Anonymous pages are associated with areas such as application heaps and stacks instead of file-backed mappings. As available physical memory decreases, the kernel attempts to reclaim pages and can move inactive anonymous pages into swap so that active workloads can continue using RAM. Because disk access is much slower than DRAM access, swap should be treated as an emergency buffer rather than a replacement for sufficient physical memory during normal workloads.

If a server has previously killed a process because memory was exhausted, swap could have provided additional time for the kernel to reclaim memory before calling the OOM killer. You can check whether this has occurred by running sudo dmesg | grep -i 'killed process' or, on Ubuntu 22.04, sudo journalctl -k | grep -i 'killed process'. A matching result indicates that available RAM was exhausted. Adding swap can lower the likelihood of similar process terminations when comparable memory pressure occurs again.

Swapfile Compared With a Swap Partition

A swap partition is a dedicated section of a disk that has been formatted specifically for swap. A swapfile is an ordinary file located on an existing filesystem that the Linux kernel treats as swap storage. Modern Ubuntu installations commonly use swapfiles because their size can be changed without repartitioning disks. The underlying filesystem still matters because certain filesystem configurations require dd rather than fallocate when creating a usable swapfile.

Feature Swap Partition Swapfile
Setup complexity Requires partition alignment and may require downtime when resizing Created using fallocate or dd and resized by replacing the file
Resize flexibility Less flexible without repartitioning or LVM More flexible because the file can be replaced before running mkswap again
Filesystem requirement Uses its own partition and does not depend on a host filesystem Stored on the root filesystem or another mounted filesystem
Ubuntu default Found on older installations and some system images Common on current Ubuntu desktop and server installations
Hibernation support Usually required for resume-to-disk configurations Normally not used for hibernation in server environments
Recommended for Legacy storage configurations and hibernation workflows Cloud servers, VPS systems, virtual machines, and flexible capacity requirements

How Much Swap Space Should Be Allocated

Select the swap size according to the amount of installed RAM and how much disk-backed paging the workload can tolerate. The following ranges are suitable for common Linux server configurations:

System RAM Recommended Swap Notes
Up to 2 GB 2x RAM Provides additional headroom for small server instances
2 to 8 GB 2 to 4 GB Suitable for typical VPS systems and web application servers
8 to 16 GB 4 GB Provides a balanced paging reserve
16 GB or more 2 to 4 GB Increase this amount only when hibernation or unusual memory spikes require it

The following examples create a 2 GB swapfile. Adjust the size parameters if your system requires a different amount.

Step 1 – Check Existing Swap Space

Check Active Swap With swapon

If no swap devices are active, the command finishes immediately without displaying any entries. When swap has already been configured, a device table appears.

NAME      TYPE  SIZE USED PRIO
/swapfile file 2G    0B   -2

Check RAM and Swap Usage With free


              total        used        free      shared  buff/cache   available
Mem:          981Mi       122Mi       647Mi       0.0Ki       211Mi       714Mi
Swap:            0B          0B          0B

When swap is enabled, the Swap row reports totals greater than zero.

Check Available Disk Space With df


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

Make sure the filesystem that will contain /swapfile, normally the root filesystem mounted at /, has sufficient free capacity for both the swapfile and expected filesystem growth.

Step 2 – Create the Swapfile

Method 1: Create a Swapfile With fallocate on ext4

fallocate can reserve the required disk capacity quickly on filesystems that create fully allocated extents that are suitable for swap.


sudo fallocate -l 2G /swapfile



-rw-r--r-- 1 root root 2.0G Apr 25 11:14 /swapfile

Select an appropriate capacity from the previous sizing table instead of automatically using the example value.

On Btrfs, files created with fallocate can contain unwritten extents that cause swapon to fail. Use the dd method when the swapfile resides on Btrfs.

Method 2: Create a Swapfile With dd on Btrfs, XFS, and Older Filesystems

dd writes zero-filled blocks and creates a completely allocated file that can satisfy the kernel’s swapfile 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

This approach takes more time than fallocate, but it creates a fully written file without sparse holes.

When to Choose fallocate or dd

Factor fallocate dd
Speed Reserves space quickly Slower because the entire file is written
Filesystem compatibility Suitable for ext4 and other filesystems that fully allocate the file Works broadly where writing from /dev/zero is supported
Sparse file risk Possible with copy-on-write or delayed-allocation configurations Low because contiguous writes populate the file
Btrfs support Not suitable for this swapfile method Use dd instead
XFS support Can be problematic for swap, so dd is preferred Preferred
Recommended for ext4 root filesystems on common Linux servers Btrfs, XFS, or situations where swapon rejects a file created with fallocate

Step 3 – Secure the Swapfile

A swapfile can contain fragments of process memory, including credentials and session-related information. Allowing other users to read it creates a potential information disclosure problem.



-rw------- 1 root root 2.0G Apr 25 11:14 /swapfile

Read and write access should remain restricted to the root user.

Step 4 – Prepare the File as Swap Space

mkswap creates the swap header, generates a UUID, and can optionally assign a label.


Setting up swapspace version 1, size = 2 GiB (2147483648 bytes)
no label, UUID=6e965805-2ab9-450f-aed6-577e74089dbf

Step 5 – Enable the Swapfile



NAME      TYPE  SIZE USED PRIO
/swapfile file 2G    0B   -2

The PRIO field displays each swap device’s priority. Linux automatically assigns negative priorities such as -2 and -3 when swap devices are enabled without an explicit priority. Devices with higher priority values are used first, so a single swapfile using -2 is sufficient. If another swap device is located on faster storage and should be preferred, assign it a higher priority using swapon -p 10 /path/to/faster-swap or add pri=10 to the options field in fstab.


              total        used        free      shared  buff/cache   available
Mem:          981Mi       123Mi       644Mi       0.0Ki       213Mi       714Mi
Swap:         2.0Gi          0B       2.0Gi

The kernel can now move memory pages into /swapfile whenever memory pressure makes swapping necessary.

Step 6 – Make the Swapfile Persistent After Reboot

The current configuration remains active only until the server restarts. Add an entry to /etc/fstab so that systemd automatically enables the swapfile during startup.

Create a backup of fstab before modifying it:

sudo cp /etc/fstab /etc/fstab.bak

Add the swap configuration:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

The fields in this entry define how systemd handles the swapfile during startup. /swapfile specifies the file path. none represents the mount point, which is not used because swap is not mounted inside the filesystem hierarchy. swap identifies the filesystem type. sw applies the normal swap options. The first 0 prevents dump from backing up this entry, while the final 0 prevents fsck filesystem checks, which are unnecessary for swap.

Check the configuration 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

An incorrect /etc/fstab configuration can stop a system from booting normally. Keep a backup of the file and verify it with sudo findmnt --verify before restarting the server.

Understanding /etc/fstab, mount configuration, filesystem layout, and Linux storage administration can also help when maintaining swap and other storage devices.

Step 7 – Tune Swap Performance With Linux Kernel Parameters

Kernel parameters determine how readily Ubuntu moves memory pages into swap and how aggressively inode and dentry caches are reclaimed. After changing these settings, monitor RSS, memory consumption, and swap activity with standard Linux resource-monitoring tools.

Adjust vm.swappiness for Server Workloads


cat /proc/sys/vm/swappiness



sudo sysctl vm.swappiness=10


Value Behavior Use Case
0 Uses swap mainly during significant memory pressure Highly latency-sensitive workloads
1 Very low tendency to swap MySQL and PostgreSQL workloads
10 Low preference for swap General Ubuntu servers, VPS systems, and cloud servers
60 Default kernel setting Desktop-oriented workload combinations
100 Swaps aggressively Rarely suitable for server workloads

Adjust vm.vfs_cache_pressure


cat /proc/sys/vm/vfs_cache_pressure



sudo sysctl vm.vfs_cache_pressure=50


vm.vfs_cache_pressure = 50

This setting controls how strongly the kernel reclaims inode and dentry caches in comparison with the page cache. A lower value causes filesystem metadata to remain cached for a longer period when the system experiences memory pressure.

Make Kernel Parameters Persistent

Ubuntu 22.04 favors configuration files under /etc/sysctl.d/ instead of placing every setting in a single configuration file. Choose one of the following methods rather than applying both, because duplicate definitions in separate files can lead to configuration drift.

Modern method:


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 method:


echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf


echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf

Apply the saved settings without restarting the system:


* Applying /etc/sysctl.d/99-swap.conf ...
vm.swappiness = 10
vm.vfs_cache_pressure = 50

How to Disable or Remove Swap Space

To stop using the swapfile temporarily without removing it from disk, run:


If no swap device remains active, sudo swapon --show produces no output and immediately returns to the terminal prompt.

An empty result confirms that swap has been disabled.

Turning off swap while applications are already experiencing memory pressure can cause the OOM killer to terminate processes. Check available memory with free -h before using swapoff.

To permanently remove the swapfile, delete the /swapfile entry from /etc/fstab, run sudo swapoff /swapfile when the swapfile is still active, and then remove the file:


After removal, verify that the totals on the Swap row have returned to zero.

Troubleshooting Common Ubuntu Swap Errors

Error Cause Fix
swapon: /swapfile: Invalid argument mkswap was not run, or the file created with fallocate is sparse, which is common on Btrfs Run sudo mkswap /swapfile, or recreate the swapfile using dd when using Btrfs
chmod: cannot access '/swapfile': No such file The swapfile was not created successfully Use df -h to check disk capacity, then run fallocate or dd again
swapon: /swapfile: swapon failed: Operation not permitted The swapfile permissions are too permissive Run sudo chmod 600 /swapfile before using mkswap
Swap is inactive after reboot The /etc/fstab entry is missing or malformed Run sudo findmnt --verify --verbose and make sure the line is /swapfile none swap sw 0 0
fallocate fails on Btrfs Btrfs cannot safely provision the swapfile through this fallocate method Remove the unfinished file using sudo rm /swapfile and recreate it with dd

Fix swapon Failed: Invalid Argument

If swap initialization was skipped, run sudo mkswap /swapfile. If the error continues, determine whether the root filesystem uses Btrfs or another copy-on-write filesystem:

If the command returns btrfs, remove the unsuitable file, rebuild it with dd, and then repeat the chmod, mkswap, and swapon commands:



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

Fix Swap Not Activating After Reboot

Check that the fstab entry contains the expected configuration:


/swapfile none swap sw 0 0

Run sudo findmnt --verify --verbose and correct any reported problems before restarting the server again.

If the fstab line is correct but /swapfile is missing, create the file again using the procedure from Step 2, then repeat chmod 600, mkswap, and swapon. This can happen after storage changes when the old /swapfile is deleted but the fstab entry is still pointing to that location. Before rebooting, confirm that the file exists with ls -lh /swapfile.

Fix Permission Denied Errors During Swapfile Creation

Make sure sudo was used when running fallocate or dd. If file creation completes successfully but swapon still reports a permission problem, restore the correct ownership and permissions:


sudo chown root:root /swapfile


Create a Swapfile on Btrfs When fallocate Fails

Use dd to allocate swap storage on Btrfs. When the swapfile is located inside a Btrfs subvolume where copy-on-write is enabled, disable CoW on the empty file before data is written. Do not use the truncate and chattr +C commands when the swapfile is stored on ext4 or XFS.


sudo truncate -s 0 /swapfile



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

Afterward, continue with the same chmod, mkswap, swapon, and fstab configuration steps.

Frequently Asked Questions About Swap Space on Ubuntu

What Is the Recommended Swap Size for an Ubuntu Server?

For systems with 2 GB of RAM or less, a swap allocation of roughly twice the installed RAM is a common guideline. Systems with 2 to 8 GB of RAM can generally use 2 to 4 GB of swap. For servers with 8 to 16 GB of RAM, approximately 4 GB of swap is suitable for many workloads. Systems with more than 16 GB of RAM commonly use 2 to 4 GB of swap unless hibernation or another special requirement needs additional capacity.

What Is the Difference Between an Ubuntu Swap Partition and a Swapfile?

A swap partition is a dedicated disk region formatted specifically for swap, while a swapfile is an ordinary file stored on an existing filesystem that the Linux kernel uses as swap. Swapfiles provide greater flexibility on modern Ubuntu systems because changing their size does not require repartitioning the disk.

Why Can fallocate Fail When Creating a Swapfile on Btrfs?

Btrfs does not guarantee that fallocate will create fully allocated extents for a swapfile, so swapon can reject the resulting file. Using dd with /dev/zero writes all blocks and satisfies the required kernel checks.

How Can Current Swap Usage Be Checked on Ubuntu?

Use sudo swapon --show to see details about individual active swap devices and free -h to view overall swap totals. Both commands show active swap only after swapon has successfully enabled it.

What vm.swappiness Value Should Be Used on an Ubuntu Server?

A value of 10 is a useful starting point for general server workloads where keeping active data in RAM is preferred over paging. Database workloads such as MySQL or PostgreSQL that can experience delays from swap reads may use 1. A value of 60 is more appropriate when desktop-style workloads justify more frequent paging.

How Can Swap Be Made Persistent After an Ubuntu Reboot?

Add /swapfile none swap sw 0 0 to /etc/fstab, verify the configuration with sudo findmnt --verify, and restart the system when appropriate. Without this fstab entry, Ubuntu does not automatically activate the swapfile at startup.

Can Swap Space Be Added to Ubuntu After Installation?

Yes. Create the swapfile, restrict its permissions, initialize it with mkswap, activate it using swapon, and add it to /etc/fstab for persistent use. Reinstalling Ubuntu is not necessary.

How Can an Existing Ubuntu Swapfile Be Increased?

To increase an ext4 swapfile from 2 GB to 4 GB, disable the existing swapfile, remove and recreate it at the new size, and then activate it again. The existing fstab entry can remain unchanged when the swapfile path stays the same.



sudo fallocate -l 4G /swapfile




Confirm the new capacity with sudo swapon --show:


NAME      TYPE  SIZE USED PRIO
/swapfile file 4G    0B   -2

If the system is experiencing memory pressure, use free -h before running swapoff to make sure enough physical RAM is available. Disabling a 2 GB swapfile while 1.5 GB of it is in use forces those pages back into RAM and can cause OOM process termination on a server with limited free memory.

Conclusion

This guide covered the process of adding swap space to Ubuntu 20.04 and Ubuntu 22.04 with a swapfile. The procedure includes checking existing memory and disk capacity, deciding between fallocate and dd, securing the swapfile permissions, preparing the file with mkswap, activating it with swapon, and making the configuration persistent through /etc/fstab after verification with findmnt. It also explained how to adjust vm.swappiness and vm.vfs_cache_pressure through /etc/sysctl.d/99-swap.conf, safely disable swap, and diagnose common swapon and fstab problems.

Swap can be configured while preparing a new cloud server, VPS, virtual machine, or physical Ubuntu system, and it can also be added to an existing server that experiences temporary increases in RAM consumption. Permission and filesystem-related problems can be resolved using the same troubleshooting procedures. Swap should remain a buffer for temporary memory pressure while applications are properly sized or additional physical resources are planned.

Source: digitalocean.com

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: