Servers with limited RAM are vulnerable to out-of-memory kills during traffic spikes or memory-intensive workloads. Swap provides an overflow area on disk, giving the kernel room to move inactive memory pages before resorting to terminating processes. This guide configures a 2 GB swap file on Ubuntu 26.04, mounts it persistently via /etc/fstab, and sets the swappiness value to a level appropriate for server workloads.
Check Current Swap
Verify memory and swap status before making any changes:
$ free -h
A Swap: 0B line confirms no swap is currently configured.
Create a Swap File
Allocate a 2 GB file, set the correct permissions, and format it as swap:
1. Create a 2 GB file:
$ sudo fallocate -l 2G /swapfile
2. Restrict file permissions:
$ sudo chmod 600 /swapfile
The chmod 600 restricts access to root only. Swap files with world-readable permissions will be rejected by the kernel.
3. Format the file as swap:
$ sudo mkswap /swapfile
Enable Swap
Activate the swap file and confirm it is recognized by the system:
1. Activate the swap file:
$ sudo swapon /swapfile
2. Verify swap is active:
$ sudo swapon --show
3. Confirm the allocation:
$ free -h
The Swap line should now show 2.0Gi total.
Configure Automatic Mounting at Boot
Swap activated with swapon does not persist across reboots without an /etc/fstab entry.
1. Back up the fstab file:
$ sudo cp /etc/fstab /etc/fstab.bak
2. Add the swap entry:
$ echo '/swapfile swap swap defaults 0 0' | sudo tee -a /etc/fstab
3. Verify the entry was written correctly:
$ grep swap /etc/fstab
Tune Swappiness
Swappiness controls how aggressively the kernel moves memory pages to swap. The value ranges from 0 to 100.
-
0— only swap when RAM is critically full -
10— recommended for servers (keeps more data in RAM) -
60— Ubuntu default (more aggressive) -
100— swap as aggressively as possible
1. Check the current value:
$ cat /proc/sys/vm/swappiness
2. Set the swappiness value:
$ sudo nano /etc/sysctl.conf
Add the following line:
vm.swappiness=10
3. Apply the change immediately:
$ sudo sysctl -p
Next Steps
Swap is now active and persists across reboots. From here you can:
- Monitor swap usage in real time with
vmstat 1during peak load periods - Increase swap size by repeating these steps with a larger
fallocatevalue - Explore
zswaporzramfor in-memory compression as an alternative to disk-backed swap
For the complete guide, visit the original article on Vultr Docs.
Top comments (0)