Configuring Swap Space on Ubuntu Linux VPS

Configuring Swap Space on Ubuntu Linux VPS

What You’ll Need

  • Hetzner VPS or Contabo VPS for hosting your Linux instance
  • DigitalOcean as an alternative cloud provider
  • A server running Ubuntu 20.04, 22.04, or 24.04 LTS
  • Root or sudo privileges on your server

Table of Contents

Understanding Swap Space on Modern Virtual Private Servers

When I spin up a new instance on a high-performance host like Hetzner VPS, one of the first configuration tasks I perform is inspecting the system memory architecture. Swap space acts as a dedicated storage area on your drive (SSD or NVMe) where the Linux kernel moves idle memory pages when physical Random Access Memory (RAM) becomes saturated.

Without swap enabled, a sudden surge in RAM usage will force the Linux Out-Of-Memory (OOM) killer daemon to step in. The OOM killer evaluates running processes, selects a target based on its internal score, and forcefully terminates it to reclaim system memory. In production, this often results in database crashes, web server outages, or ungraceful application shutdowns.

Adding swap space provides a safety cushion. While swapping memory pages to an SSD is undeniably slower than reading directly from physical RAM, it prevents hard system crashes during traffic spikes. If you run backend containers alongside background worker tasks, pairing your swap file with strict container monitor policies like Configuring Docker Compose Container Health Checks ensures your host server remains resilient under load.

Sizing Your Swap Allocation

The old rule of thumb was to allocate twice the size of your physical RAM for swap space. On modern cloud infrastructure, that formula is outdated. Here is the sizing standard I recommend for cloud VPS environments:

  1. 1GB to 2GB Physical RAM: Allocate swap equal to 1x or 2x RAM size (1GB to 4GB swap file).
  2. 2GB to 8GB Physical RAM: Allocate swap equal to 0.5x or 1x RAM size (2GB to 4GB swap file).
  3. 8GB to 32GB Physical RAM: Allocate a fixed 4GB swap file.
  4. More than 32GB Physical RAM: Allocate a 4GB to 8GB swap file, primarily for emergency dump logging and overflow protection.

Auditing System Memory and Checking Existing Swap

Before creating a new swap file on your Ubuntu server, check whether your system already has active swap partitions or files. Some cloud templates pre-configure swap, while others leave it disabled completely.

Run the swapon command with the --show flag to query active swap devices:

sudo swapon --show

If the command returns empty output, no swap space is active on your machine. You can also verify physical memory and swap allocation using the free tool with human-readable units:

free -h

The output will look similar to this on a newly provisioned 2GB RAM cloud node:

               total        used        free      shared  buff/cache   available
Mem:           1.9Gi       245Mi       1.1Gi       1.0Mi       610Mi       1.5Gi
Swap:             0B          0B          0B

Next, inspect the underlying storage volume to verify available disk capacity before allocating a file. Run df to inspect the root mount:

df -h /

Ensure your root filesystem has enough free space to accommodate the size of the swap file you intend to build.

Creating and Activating a Swap File

There are two primary utility tools used to generate swap files on Linux: fallocate and dd. The fallocate utility is significantly faster because it reserves space instantly without writing zeroes to every block. However, on certain copy-on-write filesystems such as Btrfs or ZFS, fallocate can cause allocation errors. On standard Ubuntu installations using Ext4, fallocate works reliably.

I will demonstrate both methods below. Choose option A for Ext4 filesystems, or option B as a bulletproof fallback for any storage format.

Option A: Allocating Space with fallocate

To allocate a 2GB swap file using fallocate, run the following command:

sudo fallocate -l 2G /swapfile

Verify the creation of the target file using ls:

ls -lh /swapfile

You should see output matching the specified size:

-rw-r--r-- 1 root root 2.0G Oct 24 14:00 /swapfile

Option B: Allocating Space with dd

If fallocate returns an error on your storage layer, use dd to copy zeroed blocks directly to the swap target file:

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

Securing Swap File Permissions

Swap files contain live memory structures, which may include unencrypted private cryptographic keys, user session tokens, and system secrets. To prevent unauthorized local users from reading sensitive data out of swap, restrict permissions so that only the root user can read and write to the file:

sudo chmod 600 /swapfile

Verify that permissions are locked down down to read and write for owner only (-rw-------):

ls -lh /swapfile

Output:

-rw------- 1 root root 2.0G Oct 24 14:02 /swapfile

Formatting and Enabling the Swap File

Now format the allocated space as a Linux swap structure using mkswap:

sudo mkswap /swapfile

The system will generate a response containing a unique UUID string:

Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=a1b2c3d4-e5f6-7890-abcd-1234567890ab

Activate the formatted swap file using swapon:

sudo swapon /swapfile

Confirm that the new swap file is live:

sudo swapon --show

Output:

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

💡 Fast-Track Your Project: Don’t want to configure this yourself? I build custom n8n pipelines and bots. Message me with code SYS3-HUGO.

Configuring Permanent Swap File Persistence

When you enable swap using swapon /swapfile, the settings apply only to the active runtime session. If your server reboots, the operating system forgets the swap configuration. To make this setting permanent across reboots, add an entry to the /etc/fstab table file.

Before editing, create a system backup copy of /etc/fstab:

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

Append the swap configuration entry to the end of the /etc/fstab file using tee:

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

Inspect the last lines of /etc/fstab to verify the entry was written accurately:

tail -n 2 /etc/fstab

Output:

# /etc/fstab entry for permanent swap file
/swapfile none swap sw 0 0

Tuning Linux Kernel Memory Settings for Production

Creating a swap file is only half the battle. By default, Ubuntu Linux ships with conservative kernel memory parameters optimized for desktop systems or legacy hardware. You must adjust these options to prevent system slowness on a VPS.

Two key parameters dictate how the Linux kernel uses swap memory:

  1. vm.swappiness: Controls how aggressively the kernel moves memory pages out of physical RAM into swap space. The values range from 0 to 100. A value of 0 tells the kernel to avoid swap unless RAM is completely exhausted. A value of 100 instructs the kernel to aggressively swap out cold memory pages. Default Ubuntu is typically 60.
  2. vm.vfs_cache_pressure: Controls the kernel’s tendency to reclaim memory used for caching filesystem directory and inode information. A value of 100 is neutral, while lower values keep VFS cache in RAM longer. Default Ubuntu is typically 100.

For virtual private servers running web applications, API microservices, or database engines, I recommend setting swappiness to 10 and vfs_cache_pressure to 50.

When building high-throughput webhook processing architectures, such as those described in How To Implement Idempotent Webhook Payload Processing, setting a lower swappiness value ensures your worker threads remain in physical RAM for fast execution while leaving swap available to absorb unexpected concurrency bursts.

Checking Current Kernel Settings

Read the active swappiness and cache pressure values directly from /proc:

cat /proc/sys/vm/swappiness
cat /proc/sys/vm/vfs_cache_pressure

Applying Runtime Kernel Tuning

To update these parameters dynamically without restarting your server, execute sysctl:

sudo sysctl vm.swappiness=10
sudo sysctl vm.vfs_cache_pressure=50

Making Sysctl Settings Permanent

To persist these values across system reboots, edit /etc/sysctl.conf. Append the configuration settings to the bottom of the file:

sudo bash -c 'cat <<EOF >> /etc/sysctl.conf

# Production Swap and VFS Cache Settings
vm.swappiness=10
vm.vfs_cache_pressure=50
EOF'

Apply the new configuration using the sysctl reload flag:

sudo sysctl -p

This ensures your kernel retains optimal performance characteristics when handling intensive cryptographic operations, like those involved in Implementing HMAC Signature Verification for Inbound Webhooks, without offloading hot execution frames to disk storage unnecessarily.

Managing Swap with Systemd Swap Units

While adding an entry to /etc/fstab is the traditional method for mounting swap, modern Ubuntu distributions running systemd can manage swap targets natively using unit files. This approach provides better error logging, dependency tracking, and automated service ordering during boot sequence.

If you prefer systemd management over /etc/fstab, follow these steps.

First, convert the filename path into a valid systemd unit name. Path slashes are replaced with hyphens. For /swapfile, the corresponding systemd file must be named swapfile.swap.

Create a new file at /etc/systemd/system/swapfile.swap:

sudo bash -c 'cat <<EOF > /etc/systemd/system/swapfile.swap
[Unit]
Description=Production Swap File Unit
Documentation=man:swapon(8)

[Swap]
What=/swapfile
Priority=10

[Install]
WantedBy=swap.target
EOF'

Set correct permissions on the newly created unit configuration file:

sudo chmod 644 /etc/systemd/system/swapfile.swap

Reload systemd to register the new unit file, then enable and start the service:

sudo systemctl daemon-reload
sudo systemctl enable swapfile.swap
sudo systemctl start swapfile.swap

Check the status of your systemd swap unit:

sudo systemctl status swapfile.swap

Output:

● swapfile.swap - Production Swap File Unit
     Loaded: loaded (/etc/systemd/system/swapfile.swap; enabled; vendor preset: enabled)
     Active: active since Thu 2024-10-24 14:15:00 UTC; 10s ago
               What: /swapfile
               Tasks: 0 (limit: 2340)
             Memory: 0B
                CPU: 1ms
     CGroup: /system.slice/swapfile.swap

Troubleshooting and Removing Swap Files

If you ever need to resize or remove an existing swap file from your server, follow a strict tear-down process to prevent filesystem corruption or server instability.

How to Disable and Remove a Swap File

First, stop the running swap space using swapoff:

sudo swapoff /swapfile

If you are using systemd to manage the swap lifecycle, disable and stop the systemd unit instead:

sudo systemctl stop swapfile.swap
sudo systemctl disable swapfile.swap
sudo rm /etc/systemd/system/swapfile.swap
sudo systemctl daemon-reload

If you used /etc/fstab, open /etc/fstab in a text editor and remove the line referencing /swapfile:

sudo sed -i '\|/swapfile|d' /etc/fstab

Finally, safely remove the swap file from the storage disk:

sudo rm -f /swapfile

Verify that no active swap devices remain registered:

free -h

Monitoring Real-Time Memory and Swap Usage

To view active memory transfers and identify if your system is experiencing excessive swapping (known as thrashing), monitor memory metrics in real-time using vmstat:

vmstat 2 10

This command reports memory, system swap-in (si), and swap-out (so) statistics every 2 seconds for a total of 10 iterations. If you notice non-zero values consistently under si and so during normal workload periods, your system lacks sufficient physical RAM and requires an upgraded cloud server instance.

Getting Started

Configuring a swap file is a fundamental operational step when deploying Linux applications on cloud providers like Hetzner VPS, Contabo VPS, or DigitalOcean. By setting up a dedicated swap file, locking file permissions to root, adjusting vm.swappiness down to 10, and configuring persistence via /etc/fstab or systemd, you ensure your Ubuntu server will handle application load spikes gracefully without unexpected OOM killer panics.

Outsource Your Automation

Don’t have time? I build production n8n workflows, WhatsApp bots, and fully automated YouTube Shorts pipelines. Hire me on Fiverr, mention SYS3-HUGO for priority. Or DM at chasebot.online.

Want to automate this yourself?

Start with n8n Cloud (free tier available) or self-host on a Hetzner VPS for full control.

Want this engine running on your own VPS?

This blog publishes itself — daily, unattended, on free API tiers. The full engine, Hugo theme, and setup guide are available as System 3.

Get System 3
system online