How to Configure an Extra Swap File on Ubuntu Server for Heavy Workloads

Ubuntu servers use physical RAM to run applications and process data. When a server runs out of RAM during heavy workloads (like database queries or compiling code), the Linux kernel may invoke the Out-Of-Memory (OOM) killer, forcefully terminating critical processes. To prevent this, system administrators can configure “swap space”—a designated area on the hard drive that acts as overflow memory when physical RAM is exhausted.

Why Use a Swap File Instead of a Partition?

Historically, Linux installations required a dedicated swap partition. However, modern Ubuntu systems support swap files, which are vastly superior because they can be easily resized, added, or removed on the fly without needing to repartition the underlying disk.

Step 1: Check Existing Swap Space

Before creating a new swap file, verify if the system already has swap configured:

sudo swapon --show

If the output is completely empty, the system has no active swap space.

Step 2: Create the Swap File

In this example, we will create a 4 Gigabyte (4GB) swap file using the fallocate command. It is much faster than the older dd method.

  1. Allocate the 4GB file at the root of the file system:
    sudo fallocate -l 4G /swapfile
  2. Verify the file was created with the correct size:
    ls -lh /swapfile

Step 3: Secure and Enable the Swap File

Because the swap file will contain exact copies of data in RAM—which may include passwords and sensitive information—it is critical to secure the file permissions.

  1. Restrict the file permissions so only root can read or write to it:
    sudo chmod 600 /swapfile
  2. Format the file as swap space:
    sudo mkswap /swapfile
  3. Activate the swap file on the live system:
    sudo swapon /swapfile
  4. Verify it is active:
    sudo swapon --show

Step 4: Make the Swap File Permanent

If you reboot the server now, the swap file will not be automatically mounted. You must add it to the /etc/fstab configuration file.

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

Your Ubuntu server is now equipped with an additional 4GB buffer, significantly improving stability during unexpected memory spikes and heavy computational workloads.

Get the best tech tips delivered straight to your inbox.

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