There was a problem loading the comments.

Create and enable a swap file on a Linux VPS

Support Portal  »  Knowledgebase  »  Viewing Article

  Print

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).

1) Check current memory and swap

free -h
swapon --show

2) Choose a swap size

Common starting points:

  • Small VPS (1–2 GB RAM): 1–2 GB swap
  • Medium VPS (4–8 GB RAM): 2–4 GB swap

You can adjust later if needed.

3) Create the swap file

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

4) Secure permissions

sudo chmod 600 /swapfile

5) Format and enable swap

sudo mkswap /swapfile
sudo swapon /swapfile

Verify:

swapon --show
free -h

6) Make swap permanent after reboot

Add this line to /etc/fstab:

/swapfile none swap sw 0 0

7) Optional tuning: swappiness

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

Notes

  • Swap is not a replacement for RAM. If you constantly use a lot of swap, consider upgrading the VPS plan or optimizing the workload.
  • Before making system changes, ensure you still have SSH access and know how to reach the VPS console if needed.

Share via
Did you find this article useful?  

Related Articles


Comments

Add Comment

Replying to  

Tags

© GARMTECH