Swap space extends the effective memory of a Linux server by using disk space as overflow memory. While not a substitute for RAM, it prevents out-of-memory crashes on servers that occasionally spike in memory usage. This guide creates and configures a swap file on Ubuntu 26.04 LTS.

Tested and valid on:

  • Ubuntu 26.04 LTS

Prerequisites

  • Ubuntu 26.04 LTS server
  • A user with sudo privileges
  • Sufficient free disk space (at least 1–2 GB recommended)

Step 1 – Check Current Swap

See if swap is already configured:

sudo swapon --show
free -h

Step 2 – Check Available Disk Space

Confirm you have enough free space:

df -h

Step 3 – Create a Swap File

Create a 2 GB swap file (adjust as needed — typically 1–2× RAM for small servers):

sudo fallocate -l 2G /swapfile

Step 4 – Secure the Swap File

Set strict permissions so only root can read/write it:

sudo chmod 600 /swapfile

Step 5 – Mark the File as Swap

Format the file as swap space:

sudo mkswap /swapfile

Step 6 – Enable the Swap File

Activate swap immediately:

sudo swapon /swapfile

Verify:

sudo swapon --show
free -h

Step 7 – Make Swap Permanent

Add an entry to /etc/fstab so swap survives reboots:

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

Step 8 – Tune Swappiness

swappiness controls how aggressively the kernel uses swap (0–100). A value of 10 is recommended for servers:

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

Conclusion

Your Ubuntu 26.04 LTS server now has a persistent swap file with a tuned swappiness value. Monitor RAM and swap usage over time with free -h to decide whether to increase swap or upgrade RAM.