How to Create and Manage Swap Files to Prevent Out-of-Memory Errors in Ubuntu

Deploying affordable cloud virtual private servers (VPS) or running resource-intensive compilation tasks on Ubuntu workstations with 1 GB or 2 GB of physical RAM frequently leads to unpredictable system crashes. When available physical memory drops to zero, the Linux kernel’s Out-Of-Memory (OOM) Killer abruptly terminates vital processes—crashing MySQL databases, stopping web servers, or aborting Docker containers. While repartitioning hard drives to create traditional swap partitions requires dangerous disk formatting, modern Linux distributions utilize flexible Swap Files that can be provisioned, expanded, or removed inside the existing root filesystem in minutes.

How Swap Space Protects System Stability

Swap space serves as emergency overflow virtual memory on your storage drive:

  • OOM Crash Prevention: When active programs consume all physical RAM, the Linux memory manager pages dormant background memory pages out to the swap file on disk, freeing high-speed RAM for active foreground tasks.
  • Flexible Sizing: Unlike fixed disk partitions, a swap file is simply a contiguous binary file (usually named /swapfile) that can be resized at any time without rebooting.

Step 1: Check Existing Swap Status

Before creating a swap file, verify whether your Ubuntu installation already has active swap:

sudo swapon --show
free -h

If the output table returns empty under Swap (or shows 0B), your system is operating without memory protection.

Step 2: Allocate Disk Space for the Swap File

General administrative guidelines suggest allocating swap equal to physical RAM (for machines with 2–4 GB) or 4 GB for general cloud instances. Allocate a 4 GB swap file using the fallocate utility:

sudo fallocate -l 4G /swapfile

Alternative Allocation with dd

If your filesystem does not support fallocate (or throws an unsupported error), use the classic dd utility to write zeros:

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

Step 3: Secure Permissions and Format Swap

Because swap space stores sensitive memory pages (which may include credentials or unencrypted data), you must restrict file permissions strictly to the root user:

  1. Lock down file permissions so only root can read or write:
    sudo chmod 600 /swapfile
  2. Format the allocated space as an official Linux swap area:
    sudo mkswap /swapfile

    Terminal returns the UUID and confirms: “Setting up swapspace version 1, size = 4 GiB”.

  3. Activate the swap file immediately:
    sudo swapon /swapfile

Step 4: Make the Swap File Permanent Across Reboots

Running swapon activates swap for the current session only. To make Ubuntu mount the swap file automatically on system boots, append an entry to /etc/fstab:

  1. Back up your existing filesystem table:
    sudo cp /etc/fstab /etc/fstab.bak
  2. Append the swap mount instruction:
    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Step 5: Tuning the Swappiness Parameter

The swappiness kernel parameter (ranging from 0 to 100) dictates how aggressively Ubuntu moves memory from RAM to disk:

  • swappiness = 60 (Ubuntu default): Suitable for desktop workstations.
  • swappiness = 10 (Recommended for SSD servers): Instructs the kernel to avoid swapping until physical RAM is nearly exhausted, preserving SSD lifespan and maximizing performance.

Adjusting Swappiness Dynamically

sudo sysctl vm.swappiness=10

To persist this setting across reboots, add it to /etc/sysctl.conf:

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

Swap Sizing Best Practices

Physical RAM Recommended Swap Size Ideal Swappiness
1 GB – 2 GB (Small VPS) 2 GB – 4 GB 10
4 GB – 8 GB 4 GB 10 – 20
16 GB+ 4 GB – 8 GB 10
Desktop with Hibernation Equal to RAM size + 2 GB 60

Troubleshooting and Removing Swap Files

If you ever need to delete or resize the swap file:

  1. Deactivate the swap area:
    sudo swapoff -v /swapfile
  2. Remove the /swapfile entry from /etc/fstab using sudo nano /etc/fstab.
  3. Delete the physical file:
    sudo rm /swapfile

Configuring a dedicated swap file provides essential insurance for Ubuntu servers, protecting critical background applications from catastrophic Out-of-Memory crashes.

Get the best tech tips delivered straight to your inbox.

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