When memory runs low — adding swap
When memory (RAM) runs short, programs suddenly shut down (Killed) or the server slows down as if it has frozen. Swap uses part of the disk as emergency memory, which keeps programs from being forcibly shut down when memory runs short for a moment.
Swap is much slower than real memory. If you're always short on memory, swap is only a stopgap; the real fix is moving to a plan with more memory. Moving to a new server
1. Check whether memory is low
free -h
- If the
availablevalue on theMem:line is close to 0, memory is running low. - If the
Swap:line is all 0, there's no swap.
You can check whether a program was forcibly shut down because memory ran out with the command below.
sudo dmesg | grep -i "out of memory"
If anything is printed, a program has been shut down at some point because memory ran out (OOM).
2. Create a swap file (Ubuntu, Debian)
Below is an example that creates 2GB of swap. If you have 4GB of memory or less, make it the same size as your memory; if you have more, 2–4GB is enough. First check with df -h that you have enough free disk space.
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
If you run free -h again and see 2.0Gi on the Swap: line, it worked.
3. Keep it after a reboot
As things are now, swap turns off when you reboot. Register it so it turns on automatically at boot.
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
4. Make it use swap less (optional)
With the default settings, swap gets used quite a bit even while memory is still left. With the change below, swap is only used when memory is really running out.
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system
If you want to remove swap
sudo swapoff /swapfile
sudo rm /swapfile
Then open the file with sudo nano /etc/fstab, delete the line that starts with /swapfile, and save.
What about Windows servers?
Windows has swap set up by default under the name "paging file", so you don't need to create one. If memory is running low, check which programs use the most memory in Task Manager (Ctrl + Shift + Esc) → Processes tab. For more detailed checks, see Checking a slow server.