[WordPress on VPS] How To Set and Enable Swap Space on Ubuntu

A Swap Space is a space on a hard disk used as the virtual memory extension of a computer’s real memory. Having a swap space enabled allows your computer’s operating system to pretend that you have more RAM than you actually installed, only being used mainly when there is no sufficient space in RAM left to run applications efficiently.

If you VPS is running low on memory or the MySQL server is constantly shutting down, it’s time to look the memory usage and consider to add Swap Space on your VPS if you haven’t.

Check the system for Swap information

sudo swapon --show

If you don’t see anything output back after you run the command, it means that the system doesn’t have any Swap Space available at the moment.

You can also confirm it by

free -h

Before you go ahead, you should also make sure you have enough space left to make the Swap file.

df -h

Steps to create and enable Swap Space

The general rule when it comes to how big the Swap Space should be is to double the amount of RAM you have on your system or at least the same. So, since I have a server that has 512MB or RAM, I will be creating a 1GB file here.

Create a Swap Space

sudo fallocate -1 1G /swapfile

Once succeeded, you can verify the correct amount of space was reserved by

ls -lh /swapfile

You also need to lock the file down so only the users with the root privilege can get access to the contents of the file.

sudo chmod 600 /swapfile

Check again if needed.

Enable the Swap Space

sudo mkswap /swapfile
sudo swapon /swapfile

To verify what the configuration for the Swap Space you just created and enabled, use:

sudo swapon --show
free -h

Make the Swap Space permanent

The last thing to do is to make the newly created Swap Space permanently available even after the reboot. To do so, you need to add the swap space file to the /etc/fstab file. Nano the file and add the following line at the end of the file.

/swapfile none swap sw 0 0

That’s all you need to.

Leave a Reply

Your email address will not be published. Required fields are marked *