Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Create a Swap File on a Linux VPS

Add swap space as a file, make it permanent and tune how much the system uses it.

VPS and Cloud Servers2 min read16 screenshots

Why add swap

Swap is disk space that Linux uses when RAM is full. It does not replace RAM, but it can stop programs from being killed when memory runs out. It is useful on small VPS plans.

Step 1: Check the current swap

sudo swapon --show
No swap is active
free -h
Memory and swap use

If swapon --show prints nothing, you have no swap.

Step 2: Check the free disk space

df -h
Free disk space

Step 3: Create the swap file

Create a file of 1.5 GB (change the size as you like):

sudo fallocate -l 1.5G /swap.img
Creating the swap file

Check it:

ls -lh /swap.img
The swap file in the file list

Step 4: Turn it on

Only root should read the file:

sudo chmod 600 /swap.img
Setting the permissions

Prepare it as swap:

sudo mkswap /swap.img
Making the swap area

Turn it on:

sudo swapon /swap.img
Enabling swap

Step 5: Make it permanent

Open /etc/fstab:

sudo nano /etc/fstab

Add this line at the end:

/swap.img none swap sw 0 0
The swap line in fstab

Step 6: Check it

sudo swapon --show
The active swap
free -h
Memory and swap after the change

Adjust swappiness

The swappiness value (0-100) says how eagerly the system uses swap. A low value means swap is used less. For servers, 10-20 is common.

Check the value:

cat /proc/sys/vm/swappiness
The current swappiness

Set it for now:

sudo sysctl vm.swappiness=20
Setting swappiness

Make it permanent. Open sudo nano /etc/sysctl.conf and add:

vm.swappiness=20
Swappiness in sysctl.conf

Adjust the cache pressure

vfs_cache_pressure controls how quickly the system frees the cache of file names. The default is 100.

cat /proc/sys/vm/vfs_cache_pressure
The current cache pressure
sudo sysctl vm.vfs_cache_pressure=120
Setting the cache pressure

To keep it, add vm.vfs_cache_pressure=120 to /etc/sysctl.conf too.

Remove the swap file

sudo swapoff /swap.img
sudo rm /swap.img

Then delete the line from /etc/fstab.

Quick recap

  • Make the file, set mode 600, run mkswap and swapon.
  • Add the line to /etc/fstab.
  • Tune vm.swappiness.