sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
swapon --show; free -h
On filesystems where fallocate does not work for swap, use sudo dd if=/dev/zero of=/swapfile bs=1M count=2048. Swap is a safety net, not extra RAM: a server that swaps constantly is too small. Reduce eagerness with sudo sysctl vm.swappiness=10 (persist it in /etc/sysctl.d/99-swap.conf).