How to Create a Swap File on a Linux VPS
If a small VPS keeps running out of RAM — processes getting killed, services crashing under load — a swap file gives it breathing room. Swap is disk space the system uses as overflow memory: slower than RAM, but far better than a crash when you briefly run short.
You will need root SSH access for this.
Step 1: Check whether swap already exists
swapon --show
If it returns nothing, you have no swap. Also check free memory with free -h.
Step 2: Create the swap file
Create a file (2GB is a sensible starting size for a small VPS):
sudo fallocate -l 2G /swapfile
Lock down its permissions so only root can read it:
sudo chmod 600 /swapfile
Step 3: Format and enable it
sudo mkswap /swapfile
sudo swapon /swapfile
Run free -h again and you should now see swap listed.
Step 4: Make it permanent
So swap survives a reboot, add it to /etc/fstab:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Frequently asked questions
How much swap should I create?
For small servers, 1–2× your RAM is a common guideline, but even a modest 2GB buffer prevents most out-of-memory crashes. Do not rely on huge swap as a substitute for real RAM — it is a safety net, not a performance upgrade.
Will swap slow my server down?
Only when it is actively used, because disk is slower than RAM. Light, occasional swapping is fine and protects you from crashes. Heavy, constant swapping is a sign you genuinely need more RAM — consider a larger plan.
Can I add swap on shared hosting?
No — swap is a server-level setting, so it applies to VPS and dedicated servers. On shared hosting, memory is managed for you; if you keep hitting limits, see upgrading your plan.
Was this article helpful?