Swap space extends the effective memory of a Linux server by using disk space as overflow RAM. This guide creates and configures a swap file on Ubuntu 24.04 LTS.

Tested and valid on:

  • Ubuntu 24.04 LTS

Prerequisites

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

Step 1 – Check Current Swap

See if swap is already configured:

sudo swapon --show
free -h

Step 2 – Check Available Disk Space

Confirm free space:

df -h

Step 3 – Create a Swap File

Create a 2 GB swap file:

sudo fallocate -l 2G /swapfile

Step 4 – Secure the Swap File

Set strict permissions:

sudo chmod 600 /swapfile

Step 5 – Mark the File as Swap

Format the file:

sudo mkswap /swapfile

Step 6 – Enable the Swap File

Activate swap:

sudo swapon /swapfile

Verify:

sudo swapon --show
free -h

Step 7 – Make Swap Permanent

Add to /etc/fstab:

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

Step 8 – Tune Swappiness

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 24.04 LTS server now has a persistent swap file with a tuned swappiness value. Monitor usage with free -h to decide whether to increase swap or upgrade RAM.