Global Outreach Solutions company logo — ERP, VoIP, and custom software development in PakistanGlobal Outreach
Tech Support·12 min read

How To Add Swap Space on Ubuntu 20.04

Written by Alex Garnett and Vinayak Baranwal Learn what it means for software, security, and business technology teams.

  • Tech Support
  • Swap
  • Space

By Global Outreach

Illustrated cover image for the Tech Support article "How To Add Swap Space on Ubuntu 20.04" on Global Outreach Solutions blog
  • How to Add Swap Space on Ubuntu 20.04

Written by Alex Garnett and Vinayak Baranwal

When RAM is full 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.

  • Verify existing swap with system commands before making changes.
  • Create a swapfile using appropriate methods.
  • Secure the swapfile with proper permissions.
  • Activate the swapfile and make it persistent.
  • Tune kernel parameters for optimal performance.
  • Disable or remove swap space when necessary.
  • An Ubuntu server with a non-root user having sudo privileges.
  • Enough free disk space for the swapfile.
  • Basic knowledge of using the terminal and file permissions.

On Ubuntu 20.04 and 22.04, the commands and system paths in this guide behave the same. Many cloud images may not have active swap by default, so it's essential to confirm before adding another swap device.

To check the current swap status from your server, run specific system commands.

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 the command prints nothing, no swap is active. The Swap line should read 0B for total swap in that case.

Understanding Swap Space and Its Necessity

How the Linux Kernel Utilizes Swap Space

Swap is disk-backed space the kernel uses when it cannot keep all anonymous memory pages in RAM. This helps prevent out-of-memory errors and allows workloads to continue running, albeit with reduced performance.

If your server has already terminated a process due to memory exhaustion, adding swap space can help prevent such incidents in the future by giving the kernel time to reclaim pages before invoking the OOM killer.

Swapfile vs Swap Partition: Understanding the Differences

A swap partition is a dedicated disk slice formatted for swap, while a swapfile is a regular file on an existing filesystem that the kernel uses as swap. Ubuntu defaults and many cloud images prefer swapfiles for their flexibility.

Determining the Appropriate Swap Space Allocation

The size of the swap space should be based on the amount of RAM and the tolerance for disk-backed paging. Typical guidance for Linux servers can be followed.

The examples provided use a 2 GB swapfile. Adjust the size according to your specific needs and available disk space.

Step 1: Checking Existing Swap Space

Verifying Active Swap with System Commands

When no swap devices are enabled, the command produces no output. If swap is already configured, you will see a table of devices.

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

Reading Memory and Swap Information

When swap is active, the Swap row shows nonzero totals, indicating the amount of swap space being used.

Confirming Available Disk Space

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

Ensure the mount point that will hold the swapfile has enough free space for the swapfile itself, plus additional space for normal system growth.

Step 2: Creating the Swap File

Method 1: Using fallocate for Ext4 Filesystems

fallocate is a quick method to reserve space on filesystems that support fully allocated extents, making it suitable for swap.

sudo fallocate -l 2G /swapfile
ls -lh /swapfile
-rw-r--r-- 1 root root 2.0G Apr 25 11:14 /swapfile

Choose an appropriate size for your swapfile based on your system's needs, rather than copying the example size blindly.

On Btrfs filesystems, fallocate creates files with unwritten extents, which can cause swapon to fail. In such cases, use the dd method instead.

Method 2: Using dd for Btrfs, XFS, and Older Filesystems

dd writes zero-filled blocks, producing a fully contiguous file that passes the kernel's swap header checks, although it takes longer than fallocate.

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 but ensures the file is fully allocated without holes, making it suitable for swap.

Choosing Between fallocate and dd

Step 3: Securing the Swap File

Swapfiles can contain sensitive information, such as process memory, including credentials or session data. It's crucial to secure the swapfile to prevent information disclosure.

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

Only the root user should have read and write access to the swapfile to maintain security.

Step 4: Marking the File as Swap Space

mkswap writes the swap header, assigns a UUID, and optionally a label, preparing the file for use as swap space.

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

Step 5: Enabling the Swap File

sudo swapon /swapfile

The kernel begins using the swapfile when memory pressure increases, helping to prevent out-of-memory errors.

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

The swap priority is shown, and the kernel auto-assigns negative priorities to swap devices added without an explicit priority.

Step 6: Making the Swap File Permanent

Changes made so far are temporary and will be lost upon reboot. To make the swap file permanent, add an entry to /etc/fstab.

Before editing /etc/fstab, back up the file to prevent potential boot issues.

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

Append the necessary line to /etc/fstab to make the swap file persistent across reboots.

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

The fields in the /etc/fstab entry specify how to mount the swapfile at boot, including the device path, mount point, filesystem type, and options.

Validate the syntax and mount targets to ensure the system can boot properly with the new swap file.

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 validate with system commands before rebooting.

For more information on /etc/fstab, mounting, and storage administration, refer to additional resources.

Step 7: Tuning Swap Performance with Kernel Parameters

Kernel tuning changes how the system moves pages to swap and how long cache stays warm, impacting performance.

Adjusting vm.swappiness for Server Workloads

cat /proc/sys/vm/swappiness
60
sudo sysctl vm.swappiness = 10
vm.swappiness = 10

Adjusting vm.vfs_cache_pressure

cat /proc/sys/vm/vfs_cache_pressure
100
sudo sysctl vm.vfs_cache_pressure = 50
vm.vfs_cache_pressure = 50

This parameter controls how aggressively the kernel shrinks cache versus page cache under memory pressure, affecting system performance.

Persisting Kernel Parameters

To make kernel parameter changes persistent, use the recommended approach for your system version.

Modern systems recommend using drop-in files under /etc/sysctl.d/ for persistence.

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

Alternatively, you can use a legacy method for compatibility, but avoid mixing approaches to prevent configuration issues.

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 to apply changes immediately.

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

Removing or Disabling Swap Space

To temporarily stop using the swapfile without deleting it, use the appropriate system command.

sudo swapoff /swapfile

When no swap devices are active, the command shows no output, confirming swap is inactive.

An empty result confirms that swap is inactive, and the system is no longer using the swapfile.

Disabling swap while applications are under memory pressure can trigger out-of-memory kills. Verify free memory before running the command.

To remove swap permanently, delete the /etc/fstab entry, stop the swapfile if it's active, and then delete the file itself.

sudo rm /swapfile

Confirm the swap totals return to zero after removal to ensure swap is fully disabled.

Troubleshooting Common Swap Errors

Swapon Failed: Invalid Argument Error

If swapon fails with an invalid argument error, ensure the swapfile is properly initialized and check for filesystem issues.

findmnt -no FSTYPE /

If the error persists, check the filesystem type and recreate the swapfile if necessary.

Swap Not Activating After Reboot

Confirm the /etc/fstab line matches exactly and run system commands to verify and fix any issues before rebooting again.

grep swapfile /etc/fstab
/swapfile none swap sw 0 0

If the fstab entry is correct but the file no longer exists, recreate the swapfile and re-enable it.

This often happens after a resize where the swapfile was deleted but the fstab entry was not updated.

Permission Denied During Swap File Creation

Ensure you used sudo with the appropriate command. If creation succeeds but swapon reports permission errors, reset ownership and mode.

sudo chown root:root /swapfile

Swap on Btrfs: fallocate Fails

Use dd to allocate the swapfile on Btrfs. If the swapfile is on a Btrfs subvolume with copy-on-write enabled, disable CoW on the empty file before writing data into it.

sudo truncate -s 0 /swapfile
sudo chattr +C /swapfile

Then continue with securing the swapfile, initializing it with mkswap, and enabling it with swapon, followed by updating the fstab entry.

Frequently Asked Questions

What is the Recommended Swap Size for Ubuntu Servers?

The recommended swap size depends on the amount of RAM. A general guideline is to match roughly twice the RAM when RAM is 2 GB or below.

What is the Difference Between a Swap Partition and a Swapfile on Ubuntu?

A swap partition is a dedicated disk slice formatted for swap, while a swapfile is a regular file on an existing filesystem used as swap. Swapfiles are more flexible and align with modern Ubuntu defaults.

Why Does fallocate Fail When Creating a Swapfile on Btrfs?

Btrfs does not guarantee fully allocated extents when using fallocate, which can cause swapon to reject the file. Using dd ensures every block is filled, satisfying kernel checks.

How to Check Current Swap Usage on Ubuntu

Run specific system commands to check device-level detail and aggregate totals of swap usage.

What Value Should I Set for vm.swappiness on an Ubuntu Server?

A practical starting point for Droplet workloads that prefer RAM over paging is a vm.swappiness value of 10. Adjust according to your server's specific needs and workload.

How to Make Swap Persistent After a Reboot on Ubuntu

Add the appropriate line to /etc/fstab, validate with system commands, and then reboot. Without this line, Ubuntu will not enable the swapfile automatically.

Can I Add Swap Space on Ubuntu After the Initial Installation?

Yes, you can add swap space after the initial installation by creating the swapfile, securing it, initializing it with mkswap, enabling it with swapon, and making it persistent via /etc/fstab.

How to Increase Existing Swap Space on Ubuntu

To resize an existing swapfile, disable the active swap, replace the file with a new one of the desired size, and re-enable it. The fstab entry remains the same if the path does not change.

sudo fallocate -l 4G /swapfile

Verify the new size with system commands to ensure the swapfile has been successfully resized.

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

If the system is under memory pressure, check for enough free RAM before disabling swap to avoid triggering out-of-memory kills.

Want help putting this into practice?

Global Outreach builds ERP, VoIP, and custom software for businesses in Pakistan.

Start a conversation

Related articles

← All posts