A swap file is useful if your system were to ever run out of available memory - during a spike or through normal usage. This quick article will demonstrate how to create one on your VPS and ensure it is activated on boot.

Calculating swap size

Technically, the more swap the better. However, typically we see smaller (half times RAM) swap sizes on servers with large amounts of memory (>8GB), equal or larger than the amount of RAM on servers with smaller amounts of RAM.
In this example we assume the server has 8GB RAM and we'll create a 4GB swap file.

Login to your VPS as the root user or a sudoer

Important: If you are using a sudoer, prefix all commands with sudo
Following login, make sure you have enough disk space to create the file. You can check disk usage with the df command:

df -h

Allocating space for the swap file

Assuming our swap size is 4GB:

fallocate -l 4G /swapfile

The above will create a dummy file that is 4GB in size
If the above doesn't work: (you may not have support for fallocate on certain distributions)

dd if=/dev/zero of=/swapfile bs=1M count=4k

Creating and enabling the swap file

First, turn our dummy file into swap:

mkswap /swapfile

Set permissions:

chmod 0600 /swapfile

And add this line to the file /etc/fstab:

/swapfile swap swap defaults 0 0

You can use nano, vi or your favorite text editor to edit the file, or echo to append to it:

echo "/swapfile swap swap defaults 0 0" >> /etc/fstab

Finally enable the new swap file:

swapon /swapfile

That's it. You should now have more swap and it should be automatically started on boot.

Need help?