Why a server needs swap, how to add it on Linux and FreeBSD, and when you are better off adding memory.
Swap is space on the disk where the system puts data from memory when it runs short. It doesn’t replace memory — a disk is much slower — but it is a safety net: without swap, when memory runs out the system simply stops the most memory-hungry program, and that is often the database. If you are constantly short of memory, it’s better to add more in your control panel.
To see whether you have swap now, run swapon --show and free -h (on FreeBSD, swapinfo).
Linux
A 2 GB swap file:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstabThe last line makes swap switch on again after a reboot. To stop the system moving data to disk too eagerly, lower the “swappiness”:
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swap.conf
sudo sysctl -p /etc/sysctl.d/99-swap.confTo remove swap, run sudo swapoff /swapfile, delete the line from /etc/fstab and delete the file itself.
FreeBSD
sudo dd if=/dev/zero of=/usr/swap0 bs=1m count=2048
sudo chmod 0600 /usr/swap0
echo 'md none swap sw,file=/usr/swap0,late 0 0' | sudo tee -a /etc/fstab
sudo swapon -aLOur FreeBSD images use the UFS file system, so this works. Don’t put a swap file on ZFS: the system may hang.
Didn’t find the answer? Ask our support team — we’ll help.