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
sudoaccess. - 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
- Lock the box down with SSH and UFW hardening.
- Pair this with unattended security upgrades.
- See the systemd services guide to expose memory targets per service.
Comments
0 total · 0 threads