Swap Memory in Ubuntu 24.04: Step-by-Step Setup Guide

Mastering Swap Memory in Ubuntu Server 24.04 LTS: Why You Need It & How to Set It Up

Running out of RAM on a cloud instance or dedicated server can cause catastrophic failure. When Linux encounters a sudden spike in memory usage—whether from a traffic burst to a web server, a heavy database query, or a runaway background worker—it invokes the Out of Memory (OOM) Killer. The OOM Killer forcefully terminates critical processes (often MySQL, Nginx, or Docker), crashing your applications and causing downtime.

Setting up Swap Memory acts as a crucial safety net. This guide explores what Swap memory is, why it is essential for Ubuntu Server 24.04 LTS, its primary advantages, and a step-by-step tutorial on creating, enabling, and optimizing a Swap file on your system.

What is Swap Memory?

Swap memory is a designated space on a storage drive (SSD or HDD) configured by the operating system to function as an extension of physical RAM.

When physical RAM becomes full, the Linux kernel transfers inactive or infrequently used memory pages out of RAM and writes them to the Swap space. This frees up high-speed physical memory for active operations, allowing the server to handle memory demands that temporarily exceed its physical capacity.

Why Swap Memory is Essential for Ubuntu Server 24.04 LTS

Deploying Swap memory on a production or development server provides several advantages:

1. Prevents OOM Crashing

Without Swap, if your server reaches 100% RAM utilization, kernel panic or instant process termination occurs via the OOM Killer. Swap space acts as a operational cushion, keeping key services alive during memory usage spikes.

2. Enables Memory Offloading

Linux uses physical memory not just for running applications, but also for caching files and metadata (Page Cache) to speed up disk I/O. Swap allows the OS to move dormant application memory out of RAM, leaving more high-speed memory available for active filesystem caching and active workloads.

3. Handles Unpredictable Spikes Smoothly

While Swap is slower than physical RAM (even on fast NVMe SSDs), slow performance during a traffic surge is vastly preferable to an unhandled crash or service failure.

Step-by-Step Guide: Configuring Swap Space on Ubuntu 24.04 LTS

Follow these steps to create, activate, and permanently configure a Swap file on your server.

Step 1: Check Existing Swap Configuration

Before creating a new Swap file, check whether your system already has an active Swap space.

Open your terminal and run:

Bash

sudo swapon --show

If this command yields no output, your system currently has no active Swap space. You can also verify memory utilization with:

Bash

free -h

Plaintext

               total        used        free      shared  buff/cache   available
Mem:           2.0Gi       850Mi       400Mi        12Mi       750Mi       1.0Gi
Swap:             0B          0B          0B

In the example above, Swap: 0B confirms that no Swap space is active.

Step 2: Verify Available Disk Space

Ensure you have sufficient free storage space on your root filesystem (/) to host the Swap file.

Bash

df -h

Plaintext

Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        25G  6.5G   18G  27% /

Recommended Swap Sizing Rule of Thumb:

  • RAM ≤ 2 GB: Swap size = 1.5× to 2× physical RAM.
  • RAM 2 GB – 8 GB: Swap size = Equal to physical RAM size.
  • RAM > 8 GB: Swap size = 4 GB to 8 GB (depending on system role).

For a 2 GB RAM server, a 2 GB or 4 GB Swap file is standard.

Step 3: Create a Swap File

We will create a 4 GB Swap file (/swapfile) using the fallocate utility. If fallocate is unsupported on your filesystem, dd serves as an alternative.

Method A: Using fallocate (Fastest)

Bash

sudo fallocate -l 4G /swapfile

Method B: Using dd (Fallback)

If fallocate fails or if you are using a specific file system like Btrfs, use dd:

Bash

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

Verify that the file has been created:

Bash

ls -lh /swapfile

Plaintext

-rw-r--r-- 1 root root 4.0G Jul 28 12:00 /swapfile

Step 4: Secure the Swap File Permissions

For security reasons, Swap files must strictly be readable and writeable only by the root user. Allowing standard user permissions creates a severe vulnerability where sensitive memory contents could be exposed.

Restrict permissions to 600:

Bash

sudo chmod 600 /swapfile

Verify the permission changes:

Bash

ls -lh /swapfile

Plaintext

-rw------- 1 root root 4.0G Jul 28 12:01 /swapfile

Step 5: Format and Enable the Swap File

Now format the allocated file as Swap space using mkswap:

Bash

sudo mkswap /swapfile

Plaintext

Setting up swapspace version 1, size = 4 GiB (4294967296 bytes)
no label, UUID=a1b2c3d4-e5f6-7890-abcd-ef1234567890

Enable the newly created Swap space:

Bash

sudo swapon /swapfile

Verify that Swap is active:

Bash

sudo swapon --show

Plaintext

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

Step 6: Make Swap Permanent Across Reboots

By default, Swap enabled via swapon is temporary and will be disabled upon system reboot. To make it permanent, add the /swapfile entry to /etc/fstab.

First, back up your current fstab file:

Bash

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

Append the Swap file entry to /etc/fstab:

Bash

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

Verify the contents of /etc/fstab:

Bash

cat /etc/fstab

Optimizing Swap Settings in Ubuntu 24.04

Linux provides two key kernel parameters to fine-tune how Swap memory behaves: Swappiness and Cache Pressure.

1. Adjusting swappiness

The swappiness parameter defines how aggressively the Linux kernel moves data out of physical RAM and into Swap space.

  • Value range: 0 to 100.
  • Low value (e.g., 10–20): The kernel avoids swapping unless physical RAM is nearly full.
  • High value (e.g., 60–100): The kernel actively swaps inactive pages out early.

On Ubuntu Server 24.04, the default value is usually 60. For production web or database servers, setting swappiness to 10 or 20 is recommended to prioritize physical RAM speed.

Check current swappiness:

Bash

cat /proc/sys/vm/swappiness

Set swappiness temporarily to 10:

Bash

sudo sysctl vm.swappiness=10

To make this setting permanent across reboots, edit /etc/sysctl.conf:

Bash

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

2. Adjusting vfs_cache_pressure

The vfs_cache_pressure parameter controls how aggressively the kernel reclaims memory used for caching directory and inode information versus application memory.

  • Default value: 100
  • Lowering this to 50 keeps filesystem cache in memory longer, improving overall disk performance without consuming excessive RAM.

Set vfs_cache_pressure temporarily:

Bash

sudo sysctl vm.vfs_cache_pressure=50

Make it permanent:

Bash

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

How to Remove a Swap File

If you upgrade your physical RAM later and need to remove the Swap file:

  1. Deactivate the active Swap space:Bashsudo swapoff /swapfile
  2. Remove the Swap file entry from /etc/fstab:Bashsudo nano /etc/fstab (Delete the line reading /swapfile none swap sw 0 0 and save).
  3. Delete the actual Swap file:Bashsudo rm /swapfile

Best Practices & Final Considerations

  • NVMe / SSD Endurance: Modern SSDs handle swap I/O efficiently, but setting a low swappiness value (10 to 20) helps avoid unnecessary read/write cycles.
  • Btrfs Filesystem Note: If running Ubuntu 24.04 on a Btrfs filesystem, standard fallocate or Swap files without specific flags can cause filesystem errors. Use btrfs filesystem mkswapfile on Btrfs systems.
  • Not a RAM Replacement: Swap space is a emergency safety net, not a substitute for upgrading physical RAM when running heavy workloads permanently.

By following this guide, your Ubuntu Server 24.04 LTS instance is now protected against unexpected memory exhaustion and Out of Memory crashes.

About The Author

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top