Create a swap file: more headroom for servers with little memory
Set up a swap file on Debian or Ubuntu, enable it permanently, choose the right size and control with swappiness when it is used.
When a small server runs out of memory, Linux kills programs hard, often precisely the database or the game server. A swap file is reserve memory on the disk: much slower than RAM, but it absorbs short spikes, for example while building an application or during an update.
Swap is a safety net, not a replacement for RAM. If a server is permanently in swap, it becomes noticeably slow. Then a larger plan is the right solution.
Is there swap already?
swapon --show
free -h
If swapon --show prints nothing, there is no swap.
Which size?
| Memory | recommended swap |
|---|---|
| 1 GB | 1 to 2 GB |
| 2 to 4 GB | 2 GB |
| 8 GB and more | 2 to 4 GB |
Create the swap file
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
chmod 600 is important: parts of the memory can end up in swap, including passwords. Only root may read the file.
If fallocate reports an error (on some file systems), use this instead:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
Enable it permanently
Without this step the swap is gone after the next reboot:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Check the file afterwards with cat /etc/fstab. A typo in fstab can hold up the boot.
swappiness: when does Linux swap?
vm.swappiness (0 to 100) determines how early Linux swaps. The default of 60 is meant for desktops. On servers a low value is better, so that everything stays in fast RAM as long as possible:
cat /proc/sys/vm/swappiness
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system
Resize or remove
sudo swapoff /swapfile
sudo rm /swapfile
Then either create it again (see above) or delete the line from /etc/fstab.
Who uses the memory?
free -h
ps aux --sort=-%mem | head -n 10
Or more clearly with htop (sudo apt install htop); press M to sort by memory. If a program was killed because of low memory, find it with:
journalctl -k | grep -i "out of memory"
For the community
Know your stuff? Write a guide.
Share what you know: we review every submitted guide, publish it under your name and say thank you with credit for your services.