Community Tutorials Ubuntu How to Set Up Swap on Ubuntu 24.04
How to Set Up Swap on Ubuntu 24.04
UBUNTU

How to Set Up Swap on Ubuntu 24.04

SKYLINE Knowledge Base
Photo by Taylor Vick on Unsplash

A field-tested, step-by-step guide. How to Set Up Swap on Ubuntu 24.04 — prerequisites, the actual commands, verification, and links to related Ubuntu topics.

Out of the box Ubuntu Server 24.04 ships without a swap file on most cloud images. For workloads that occasionally spike, a small swap file is the cheapest insurance against the OOM-killer.

Prerequisites

  • Ubuntu Server 22.04 or 24.04 with sudo access.
  • At least 2 GiB of free space on the root filesystem.
  • An idea of how much swap you actually want — for general use, swap = min(RAM, 4G).

Step 1: Check existing swap

free -h
swapon --show

If swapon --show returns nothing, you have zero swap. Continue.

Step 2: Create the swap file

We will allocate 2 GiB. Use fallocate for speed; fall back to dd if the filesystem (some tmpfs, NFS, etc.) does not support it.

sudo fallocate -l 2G /swapfile
# fallback if fallocate fails:
# sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Confirm:

swapon --show
free -h

Step 3: Persist across reboots

swapon is in-memory only. Add a line to /etc/fstab:

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

Verify the entry is correct and the file mounts cleanly:

sudo swapoff /swapfile
sudo swapon -a
swapon --show

Step 4: Tune swappiness

vm.swappiness controls how aggressively the kernel swaps. The default of 60 is too eager for servers; 10 is a sensible production value.

sudo sysctl vm.swappiness=10
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-skyline-swap.conf

Verify

cat /proc/swaps
sysctl vm.swappiness

/proc/swaps should list /swapfile, and vm.swappiness should return 10.

Conclusion

A right-sized swap file (with low swappiness) costs nothing and stops the OOM-killer from picking off your application during a brief memory spike. Keep an eye on swapon --show over the first week — chronic swap-in is a sign you actually need more RAM.

Next steps

SKYLINE Engineering

@skyline

The engineering team at SKYLINE Industrial Solutions. We publish field-tested guides drawn from real KSA and GCC deployments.

See author profile
SKYLINE engineering services

Need this implemented for you?

Reading is free — building it right takes a team. SKYLINE engineers ship Ubuntu for Aramco vendors, banks, hospitals and government agencies across Saudi Arabia. Talk to us before you start.

Aramco Approved Contractor ISO 9001 · ISO 27001 SAMA CSF aligned NCA ECC ready 247+ KSA clients

Comments

0 total · 0 threads
Be the first to leave a comment.