惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
云风的 BLOG
云风的 BLOG
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
Vercel News
Vercel News
Y
Y Combinator Blog
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Check Point Blog
M
MIT News - Artificial intelligence
Jina AI
Jina AI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
Hugging Face - Blog
Hugging Face - Blog
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
F
Fortinet All Blogs
博客园 - 司徒正美
I
InfoQ
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
U
Unit 42

DigitalOcean Community Tutorials

It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go How To Set Up Time Synchronization on Ubuntu
How to Add Swap Space on Ubuntu
Alex Garnett · 2022-04-26 · via DigitalOcean Community Tutorials

Introduction

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.

Key Takeaways

  • Verify existing swap with sudo swapon --show and free -h before making changes.
  • Create a swapfile with fallocate on ext4, or with dd on Btrfs, XFS, or older filesystems where sparse allocation breaks swapon.
  • Secure the swapfile with chmod 600, initialize it with mkswap, and activate it with swapon.
  • Persist swap across reboots by appending /swapfile none swap sw 0 0 to /etc/fstab, then validate with sudo findmnt --verify --verbose before rebooting.
  • Tune vm.swappiness and vm.vfs_cache_pressure for server workloads, and store permanent values under /etc/sysctl.d/ on Ubuntu 22.04.
  • Disable swap temporarily with swapoff, or remove the fstab entry and delete /swapfile to drop swap permanently.
  • Recover from common failures such as swapon invalid argument errors, permission problems, Btrfs fallocate issues, and fstab mistakes.

Prerequisites

  • An Ubuntu 20.04 or Ubuntu 22.04 server and a non-root user with sudo privileges. If you have not configured that yet, follow Initial Server Setup with Ubuntu 22.04.
  • At least 2 GB of free disk space on the filesystem that will hold /swapfile for a typical allocation (adjust upward if you choose a larger swapfile).
  • Comfort using the terminal and basic file permissions.

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:

  1. sudo swapon --show
  1. 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.

What Is Swap Space and When Do You Need It

How the Linux Kernel Uses Swap

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.

Swapfile vs Swap Partition

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

How Much Swap Space to Allocate

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.

Step 1 - Check Existing Swap Space

Verify Active Swap with swapon

  1. 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

Read Memory and Swap with free

  1. 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.

Confirm Available Disk Space with df

  1. 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.

Step 2 - Create the Swap File

fallocate reserves space quickly on filesystems that write fully allocated extents suitable for swap.

  1. sudo fallocate -l 2G /swapfile
  1. 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.

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

dd writes zero-filled blocks and produces a fully contiguous file that passes the kernel’s swap header checks.

  1. 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.

When to Use fallocate vs dd

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

Step 3 - Secure the Swap File

Swapfiles can contain remnants of process memory, including credentials or session material. World-readable swap is an information disclosure risk.

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

Only the root user should retain read and write bits.

Step 4 - Mark the File as Swap Space

mkswap writes the swap header, assigns a UUID, and optionally a label.

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

Step 5 - Enable the Swap File

  1. sudo swapon /swapfile
  1. 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.

  1. 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.

Step 6 - Make the Swap File Permanent

Changes so far apply until reboot. Add an /etc/fstab entry so systemd mounts swap automatically.

Back up fstab before editing:

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

Append the swap line:

  1. 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:

  1. 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.

Step 7 - Tune Swap Performance with Kernel Parameters

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.

Adjust vm.swappiness for Server Workloads

  1. cat /proc/sys/vm/swappiness
60
  1. 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

Adjust vm.vfs_cache_pressure

  1. cat /proc/sys/vm/vfs_cache_pressure
100
  1. 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.

Persist Kernel Parameters

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

  1. echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swap.conf
  1. echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.d/99-swap.conf

Legacy compatible:

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

Reload settings without rebooting:

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

How to Remove or Disable Swap Space

Temporarily stop using the swapfile without deleting it:

  1. sudo swapoff /swapfile
  1. 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:

  1. sudo rm /swapfile
  1. free -h

Confirm the Swap totals return to zero after removal.

Troubleshooting Common Swap Errors

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

Swapon Failed: Invalid Argument

Run sudo mkswap /swapfile if you skipped initialization. If the error persists, check whether the root filesystem is Btrfs or another CoW filesystem:

  1. findmnt -no FSTYPE /

If the result is btrfs, remove the bad file and recreate it with dd, then repeat chmod, mkswap, and swapon:

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

Swap Not Activating After Reboot

Confirm the fstab line matches exactly:

  1. 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.

Permission Denied During Swap File Creation

Ensure you used sudo with fallocate or dd. If creation succeeds but swapon reports permission errors, reset ownership and mode:

  1. sudo chown root:root /swapfile
  1. sudo chmod 600 /swapfile

Swap on Btrfs: fallocate Fails

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.

  1. sudo truncate -s 0 /swapfile
  1. sudo chattr +C /swapfile
  1. sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

Then continue with chmod, mkswap, swapon, and fstab as before.

Frequently Asked Questions

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.

What is the difference between a swap partition and a swapfile on Ubuntu?

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.

Why does fallocate fail when creating a swapfile on Btrfs?

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.

How do I check current swap usage on Ubuntu?

Run sudo swapon --show for device-level detail and free -h for aggregate totals. Both commands reflect active swap only after swapon succeeds.

What value should I set for vm.swappiness on an Ubuntu server?

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.

How do I make swap persistent after a reboot on Ubuntu?

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.

Can I add swap space on Ubuntu after the initial installation?

Yes. Create the swapfile, lock permissions, run mkswap, enable with swapon, and persist via /etc/fstab. No reinstall is required.

How do I increase existing swap space on Ubuntu?

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.

  1. sudo swapoff /swapfile
  1. sudo rm /swapfile
  1. sudo fallocate -l 4G /swapfile
  1. sudo chmod 600 /swapfile
  1. sudo mkswap /swapfile
  1. sudo swapon /swapfile

Verify the new size with sudo swapon --show:

  1. 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.

Conclusion

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.

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.