Swap is disk space that Linux can use when RAM pressure gets high. It is slower than real memory, but it can keep a small VPS or a memory-hungry maintenance job from falling over immediately.
This is the short version I use for Ubuntu servers when I need a swap file, not a separate swap partition.
Check Current Swap
swapon --show
free -h
If swapon --show already lists a swap device or file, do not add another one blindly. Decide whether you want more swap, a different priority, or no change at all.
Create the File
Pick a size. For a small VPS, 2-4 GB is often enough. Here I will create a 4 GB file at /swapfile.
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
The permissions matter. swapon rejects world-readable swap files because swap may contain private process memory.
If fallocate is not supported by the filesystem, or if swapon later complains about holes in the file, use dd instead:
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
sudo chmod 600 /swapfile
The swapon(8) manual notes that swap files with holes can be rejected, and that dd is the most portable way to create a populated swap file.
Format and Enable It
sudo mkswap /swapfile
sudo swapon /swapfile
Verify:
swapon --show
free -h
You should see /swapfile in the swapon --show output and non-zero swap in free -h.
Enable It After Reboot
Back up /etc/fstab first:
sudo cp /etc/fstab /etc/fstab.bak
Add the swap entry:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
The none target is conventional for swap entries. swapon --all reads swap entries from /etc/fstab during boot.
If you want to test the entry without rebooting:
sudo swapoff /swapfile
sudo swapon -a
swapon --show
Only do this when the machine is not under heavy memory pressure.
Optional: Tune Swappiness
vm.swappiness controls how eagerly the kernel tends to use swap. The default may be fine. On many small servers, I prefer a lower value so swap is a safety net rather than a place the system uses eagerly.
Check the current value:
cat /proc/sys/vm/swappiness
Set it until reboot:
sudo sysctl vm.swappiness=10
Persist it:
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
Do not tune this by folklore. If the machine is swapping constantly, it probably needs less memory pressure or more RAM, not a prettier swappiness value.
Rollback
To remove the swap file:
sudo swapoff /swapfile
sudo sed -i.bak '\|/swapfile none swap|d' /etc/fstab
sudo rm /swapfile
Then verify:
swapon --show
free -h
Caveats
- Do not put a swap file on NFS.
- Be careful on Btrfs and other copy-on-write filesystems; swap files have extra constraints there.
- If hibernation/resume matters, a swap file is not just “add swap and forget it”. Resume configuration is a separate topic.
- Swap is not a replacement for memory planning. It is a pressure valve.