Swap is disk space that Linux uses when the RAM is full. On a small VPS it keeps your apps alive during a short memory peak, for example while packages install, a project builds or a database runs a big query. Without swap, the kernel's out-of-memory killer stops a process to free memory, usually the one that uses the most: often your database or your app.
Swap is much slower than RAM, so it is a safety net, not a replacement for more memory. The commands are for Ubuntu and Debian and use sudo.
1. Check what you have
free -h
swapon --show If swapon --show prints nothing, the server has no swap yet.
2. Choose a size
Swap takes disk space away from your files, so keep it moderate:
| RAM of your plan | Swap |
|---|---|
| 1 GB (for example the $1 Server) | 1 GB |
| 2–4 GB (for example Virtual-1) | 2 GB |
| 8 GB or more | 2 GB is plenty, and often none is needed |
Check the free disk space with df -h / first. The examples below create 1 GB; for 2 GB use 2G and count=2048.
3. Create and turn on the swap file
sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile If fallocate fails, or swapon reports invalid argument, remove the file and create it with dd instead (this takes a few seconds):
sudo rm /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress Then run the chmod, mkswap and swapon lines again.
4. Keep it after a reboot
Add the swap file to /etc/fstab (the grep part makes sure the line is only added once), then test the entry:
grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
sudo swapoff /swapfile
sudo swapon -a
swapon --show swapon -a turns on everything listed in /etc/fstab, so if /swapfile shows up again, it will also come back after a reboot.
5. Use swap only when it's really needed
With the default setting (60), Linux moves memory to swap fairly early to keep more disk cache. A lower swappiness keeps your apps in RAM as long as possible:
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system
cat /proc/sys/vm/swappiness The last command should print 10.
When swap isn't enough
Run free -h now and then. A little swap in use is normal. If swap is always busy and the server feels slow, your apps need more RAM than the plan has. Find the biggest memory users with:
ps aux --sort=-rss | head -n 10 Then trim those apps, or move to a bigger plan.
Remove the swap file
sudo swapoff /swapfile
sudo sed -i '\|^/swapfile |d' /etc/fstab
sudo rm /swapfile Last updated 2026-11-08. Need help? Open a ticket – our team answers 24/7.