If your Linux VPS runs out of RAM, processes can be killed by the OOM killer and services may crash. Adding swap gives the system extra virtual memory on disk (slower than RAM, but useful as a safety buffer).
free -h
swapon --show
Common starting points:
You can adjust later if needed.
Example for a 2 GB swap file:
sudo fallocate -l 2G /swapfile
If fallocate is not available, use dd:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Verify:
swapon --show
free -h
Add this line to /etc/fstab:
/swapfile none swap sw 0 0
Swappiness controls how aggressively Linux uses swap. Example (temporary until reboot):
sudo sysctl vm.swappiness=10
To make it permanent, add to /etc/sysctl.conf:
vm.swappiness=10