There was a problem loading the comments.

How to Add a Swap File on a Linux VPS

Support Portal  »  Knowledgebase  »  Viewing Article

  Print

Quick answer: Add swap on a Linux VPS by creating a file with fallocate, setting chmod 600, running mkswap and swapon, then adding it to /etc/fstab so it survives reboot. Lower vm.swappiness to about 10 so swap is used only under memory pressure. Swap prevents crashes but is slower than RAM.

A swap file gives a Linux VPS extra virtual memory on disk, which prevents processes from being killed when RAM runs out. It is a cheap safety net for memory spikes, especially on smaller plans. Here is how to add one safely.

1. Check whether swap already exists

swapon --show
free -h

If the output is empty or shows 0 swap, continue. If swap already exists, you usually do not need more.

2. Create the swap file

A common size is equal to your RAM, up to about 4 GB. Create a 2 GB file:

fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

The chmod 600 is important - the swap file must be readable only by root.

3. Make it permanent

So swap survives a reboot, add it to /etc/fstab:

echo '/swapfile none swap sw 0 0' >> /etc/fstab

4. Tune how aggressively it is used

Swappiness controls how readily Linux moves data to swap. For a server, a lower value keeps more in fast RAM and uses swap only under pressure:

sysctl vm.swappiness=10
echo 'vm.swappiness=10' >> /etc/sysctl.conf

5. Verify

free -h
swapon --show

You should now see the swap space active. Remember that swap is slower than RAM - it prevents crashes but is not a substitute for enough memory. If the server swaps constantly, the real fix is more RAM or lighter workloads.

Frequently asked questions

How much swap should I create?
A common choice is equal to RAM, up to about 4 GB.

Is swap a substitute for more RAM?
No - it prevents out-of-memory crashes but is slower; constant swapping means you need more RAM.

If your applications regularly outgrow their memory, a right-sized plan solves it properly: a SoftSys managed Linux VPS can be scaled to more RAM without rebuilding, and our team will advise on the correct size for your workload.


Share via
Did you find this article useful?  

Related Articles

Tags

© Softsys Hosting