How to Create and Manage Swap Files on Ubuntu

Why Swap Space Is Critical for Linux System Stability

When physical RAM (Random Access Memory) on an Ubuntu machine becomes fully saturated, the Linux kernel encounters an immediate operational crisis. If no secondary memory pool exists, the kernel’s Out-Of-Memory (OOM) killer activates, violently terminating arbitrary processes—such as databases, web servers, or active user sessions—to prevent a complete kernel panic. This scenario is particularly common on affordable cloud VPS instances (which often run with 1 GB or 2 GB of RAM) and workstations running heavy background compilations or containerized workloads.

Swap space acts as a safety valve. When active memory usage nears capacity, the Linux kernel offloads inactive or dormant memory pages from physical RAM onto your high-speed SSD storage. While traditional Linux installations historically relied on dedicated hard drive swap partitions, modern Ubuntu releases (including Ubuntu 24.04 LTS and 22.04 LTS) use swap files. Swap files can be dynamically resized, added, or removed without repartitioning your drives or restarting your server.

Step 1: Check Your Current Swap Usage and Disk Capacity

Before adding a swap file, verify whether your Ubuntu system already has active swap space and ensure your root filesystem has sufficient free storage.

Open your terminal and run the following command:

sudo swapon --show

If the command outputs nothing, your system currently has no swap active. Alternatively, view your memory summary:

free -h

Next, confirm you have sufficient free SSD space to allocate for your new swap file:

df -h /

Ensure the Avail column shows more than the amount of swap you plan to allocate (e.g. at least 4 GB or 8 GB of free space).

Step 2: Allocate the Swap File (fallocate vs dd)

The fastest and most efficient way to preallocate a swap file in modern Ubuntu is using fallocate. In this example, we will create a 4 GB swap file named /swapfile:

sudo fallocate -l 4G /swapfile

Verify that the file was created with the correct size:

ls -lh /swapfile

Alternative: Using dd for Copy-On-Write Filesystems (Btrfs/ZFS)

If you are using a filesystem where fallocate reports an allocation failure (or when running on certain older kernels), allocate the file block-by-block using dd:

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

Step 3: Secure File Permissions (Crucial Security Step)

A swap file contains raw memory pages, which may include plaintext passwords, encryption keys, and private application telemetry. By default, world-readable files represent an extreme security vulnerability. Restrict permissions strictly to root:

sudo chmod 600 /swapfile

Confirm the permissions reflect -rw-------:

ls -l /swapfile

Step 4: Format and Activate the Swap File

Format the allocated file as a dedicated Linux swap area:

sudo mkswap /swapfile

The system will output a confirmation displaying the swap size and a unique UUID. Now, enable the swap file:

sudo swapon /swapfile

Verify that Ubuntu is now utilising the swap space:

sudo swapon --show
free -h

You should see /swapfile active with 4.0G of total capacity.

Step 5: Make the Swap File Permanent Across System Reboots

Running swapon only activates the file for your current session. When the machine restarts, the file will remain on disk but will not activate automatically. To make it permanent, add an entry to your filesystem table (/etc/fstab).

1. Back up your existing /etc/fstab file:

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

2. Append the swap entry to /etc/fstab:

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

Step 6: Optimise Swappiness and Cache Pressure

The Linux kernel uses a parameter called swappiness (a value from 0 to 100) to determine how aggressively it transfers data from RAM into swap. Ubuntu defaults to a swappiness value of 60, which is often too aggressive for desktop workstations and SSD-based servers.

  • Swappiness = 60: Aggressive swapping; suitable for older mechanical spinning drives.
  • Swappiness = 10: Recommended for modern SSDs and servers. The kernel will only swap when physical RAM is under real pressure.

Checking and Adjusting Swappiness

Check your current swappiness value:

cat /proc/sys/vm/swappiness

Temporarily set swappiness to 10:

sudo sysctl vm.swappiness=10

To make this setting permanent across reboots, append it to /etc/sysctl.conf:

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

Frequently Asked Questions

How much swap space should I allocate on Ubuntu?

A good rule of thumb is: if you have 2 GB or less of RAM, allocate 2x your RAM (e.g. 2 GB to 4 GB). For systems with 4 GB to 16 GB of RAM, allocate an amount equal to your RAM. For machines with 32 GB or more of RAM, 4 GB to 8 GB of swap is typically plenty to handle unexpected memory spikes.

How do I remove or delete a swap file?

To safely delete a swap file: first disable it with sudo swapoff -v /swapfile, remove the corresponding line from /etc/fstab, and finally delete the file with sudo rm /swapfile.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.