Swap — Extra Memory on Disk
When RAM runs out, Linux can move memory it hasn't touched lately out to disk: swap. Disk is far slower than RAM — but instead of the out-of-memory killer ending your database, the server only slows down for a while. Most cloud servers start without any:
free -h
total used free shared buff/cache available
Mem: 2.0Gi 305Mi 1.4Gi 18Mi 307Mi 1.5Gi
Swap: 0B 0B 0B
A swap file is the easy way — no partition needed:
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
fallocatemakes a 2 GiB file and reserves all its space at once.chmod 600— only root may read it: it can hold anyone's memory, passwords included.mkswapwrites the swap header.swaponputs it to use.
swapon --show
free -h
NAME TYPE SIZE USED PRIO
/swapfile file 2G 0B -2
Every boot
swapon lasts until the next reboot. One line in /etc/fstab makes it permanent:
/swapfile none swap sw 0 0
sudo swapon -a turns on every swap in fstab — the test, like mount -a.
| RAM | Swap to start with |
|---|---|
| up to 2 GB | as much as the RAM |
| 4–8 GB | 2–4 GB |
| 16 GB and more | 4 GB |
💡
truncate -s 2Gmakes a file with holes — mkswap warns about it and swapon refuses it. That's whyfallocate.