Website Vidya
Linux & ServersStep-by-Step Guide

How to Add Swap Space on Ubuntu 24.04 and 22.04

Learn how to add swap space on ubuntu 24.04 with fallocate, mkswap, swapon, permanent /etc/fstab entries, swappiness tuning, and removal steps.

RR
Rajesh RayLead Systems Educator
Published:
6 min read
PDF Cheat Sheet
How to Add Swap Space on Ubuntu 24.04 and 22.04
AI Executive SummaryWebsiteVidya AI

6 min read

Learn how to add swap space on ubuntu 24.04 with fallocate, mkswap, swapon, permanent /etc/fstab entries, swappiness tuning, and removal steps.

Key Highlights
  • Prerequisites and Supported Releases
  • Step 1: Checking Existing Swap Space on Ubuntu
  • Step 2: Creating a Swap File with fallocate or dd
Grounded in full engineering runbookWebsiteVidya AI Engine

Physical Random Access Memory (RAM) is often one of the most constrained hardware resources on cloud virtual machines, budget VPS instances, and development workstations.

When system memory becomes exhausted by intensive background processes, database queries, or application build jobs, the Linux Out-Of-Memory (OOM) killer abruptly terminates running processes to protect the kernel from crashing.

Configuring swap space allows the Linux kernel to temporarily offload inactive memory pages to disk storage, providing an essential safety buffer that prevents memory allocation crashes and keeps services responsive during sudden traffic spikes.

In this guide, we demonstrate how to add swap space on ubuntu 24.04 step-by-step using dedicated swap files, configure permanent boot mounts, tune kernel memory aggressiveness, and verify memory metrics.

Advertisement

Prerequisites and Supported Releases

This guide is thoroughly verified on Ubuntu 24.04 LTS (Noble Numbat) & Ubuntu 22.04 LTS. The instructions apply cleanly to cloud instances (AWS EC2, Google Compute Engine, DigitalOcean, Hetzner), bare-metal servers, and local virtual machines.

Before proceeding, ensure you have the following requirements satisfied:

  • A server or computer running Ubuntu 24.04 LTS or Ubuntu 22.04 LTS.
  • A non-root user account with sudo administrative privileges.
  • Sufficient free hard disk or SSD storage (typically 2 GB to 8 GB depending on RAM size).

Step 1: Checking Existing Swap Space on Ubuntu

Before creating a new swap file, verify whether your operating system already has swap partitions or swap files configured.

Advertisement

Use the swapon --show utility and the free -h command to inspect current memory and swap allocation:

If the output returns an empty summary or displays 0B under Swap, your system currently operates without any swap protection:

# Check active swap devices and files:
sudo swapon --show

# Display current RAM and Swap utilization in human-readable format:
free -h
# Example output:
#                total        used        free      shared  buff/cache   available
# Mem:           1.9Gi       480Mi       890Mi        12Mi       610Mi       1.3Gi
# Swap:             0B          0B          0B

# Check available disk storage space on the root filesystem:
df -h /

Step 2: Creating a Swap File with fallocate or dd

The fastest and most efficient way to allocate space for a swap file is using the fallocate utility.

As a general sizing rule: for servers with 2 GB or less RAM, configure swap equal to or double your RAM; for systems with 4 GB to 16 GB, a 2 GB to 4 GB swap file is typically sufficient.

Advertisement

Run fallocate to create a 2 GB file named /swapfile:

If your filesystem (such as Btrfs) does not support fallocate, allocate the file using dd as an alternative:

# Allocate a 2 Gigabyte swap file instantly using fallocate:
sudo fallocate -l 2G /swapfile

# Alternative allocation using dd (use if fallocate fails on your filesystem):
# sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

# Verify allocated file size on disk:
ls -lh /swapfile
# Output confirms: -rw-r--r-- 1 root root 2.0G ... /swapfile

Step 3: Setting Secure Permissions on the Swap File

Because swap files contain raw memory pages, sensitive data—such as plaintext passwords, cryptographic private keys, and application tokens—can reside inside.

Restricting read and write access strictly to the root user is mandatory for server security.

Use chmod 600 to prevent non-root users from reading swap data:

# Restrict file permissions strictly to root:
sudo chmod 600 /swapfile

# Verify that permissions are set to -rw-------:
ls -lh /swapfile
# Output confirms: -rw------- 1 root root 2.0G ... /swapfile

Step 4: Formatting and Activating the Swap File

Once created and secured, format the file as a Linux swap area using the mkswap command.

Next, enable the swap space in the running kernel using swapon:

Verify that the kernel recognized and attached the new swap allocation:

# Format the file as a Linux swap area:
sudo mkswap /swapfile
# Output confirms: Setting up swapspace version 1, size = 2 GiB ... UUID=...

# Enable the swap space:
sudo swapon /swapfile

# Verify that swap is active:
sudo swapon --show
# Output confirms: NAME=/swapfile TYPE=file SIZE=2G USED=0B PRIO=-2

# Check memory status with free -h:
free -h
# Output confirms: Swap: 2.0Gi 0B 2.0Gi

Step 5: Making Swap Permanent Across System Reboots (/etc/fstab)

Manual swapon activations only persist until the system reboots.

To ensure the swap space mounts automatically upon system startup, append an entry to /etc/fstab.

Always back up /etc/fstab before modifying it, then append the swap entry:

# Backup fstab before editing:
sudo cp /etc/fstab /etc/fstab.bak

# Append swapfile configuration to /etc/fstab:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Test fstab configuration syntax:
sudo mount -a

Step 6: Tuning Swappiness and Cache Pressure

The swappiness kernel parameter defines how aggressively the Linux kernel moves memory pages from physical RAM to swap space.

Swappiness is an integer between 0 and 100. Ubuntu defaults to 60, which is optimized for desktop responsiveness but often too aggressive for database and web servers.

For production servers, lowering swappiness to 10 ensures swap is used only when physical RAM is genuinely running low:

You can also tune vfs_cache_pressure to prevent the kernel from dropping inode and dentry caches prematurely:

# Check current swappiness value:
cat /proc/sys/vm/swappiness
# Default output: 60

# Temporarily set swappiness to 10:
sudo sysctl vm.swappiness=10

# Check cache pressure:
cat /proc/sys/vm/vfs_cache_pressure
# Default output: 100

# Make kernel parameters permanent in /etc/sysctl.conf:
cat << 'EOF' | sudo tee -a /etc/sysctl.conf
vm.swappiness=10
vm.vfs_cache_pressure=50
EOF

# Apply sysctl settings immediately:
sudo sysctl -p

Troubleshooting and Common Errors

When configuring Ubuntu servers, unexpected permission errors, network timeouts, or lock contention can occur. Review these common issues and verified resolutions:

fallocate failed: Operation not supported

Cause: Certain filesystems (such as Btrfs or ZFS) do not support allocating unwritten extents for swapfiles via fallocate.

Resolution: Create the swap file using dd: sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress.

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

swapon: /swapfile: insecure permissions 0644, 0600 suggested

Cause: The swap file permissions allow non-root users to read or write data.

Resolution: Restrict permissions immediately using sudo chmod 600 /swapfile.

sudo chmod 600 /swapfile

swapon failed: Device or resource busy

Cause: The specified swap file is already active and attached to the kernel.

Resolution: Check active swap using sudo swapon --show; to reload it, run sudo swapoff /swapfile && sudo swapon /swapfile.

sudo swapon --show

Security Best Practices and Hardening

Always set file permissions to 600 so unprivileged system users cannot read raw RAM dumps containing passwords and authentication secrets.

If running encrypted disks (LUKS), ensure swap is allocated within an encrypted logical volume or encrypted swap partition to prevent plaintext memory leaks to physical storage.

Do not configure excessive swap on slow mechanical hard drives, as heavy swapping ('thrashing') can freeze the operating system.

Deepen your Linux system administration skills with our related production-tested guides:

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
For systems with up to 2 GB RAM, allocate double the RAM size (2 GB to 4 GB swap). For systems with 4 GB to 16 GB RAM, allocate equal or half RAM (4 GB to 8 GB swap). For large servers with 64 GB+ RAM, 4 GB to 8 GB swap is typically adequate.
A swap partition is a dedicated, separate disk partition formatted specifically for swap. A swap file is a standard file on an existing filesystem. Modern Linux kernels handle swap files with virtually identical performance to swap partitions, with the added benefit of being easy to resize without repartitioning disks.
First disable swap using sudo swapoff /swapfile, remove the /swapfile entry from /etc/fstab, and finally delete the file with sudo rm -f /swapfile.
No. Disk storage (even fast NVMe SSDs) is orders of magnitude slower than physical RAM. Swap is designed as an overflow buffer to prevent Out-Of-Memory crashes, not as a substitute for adequate physical memory.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout