How to Setup Creat Swap on Linux on VULTR VPS

here will be times where you need to increase the responsiveness of your server to prevent out of memory issues. Out of memory issues happen when an application running on your server starts consuming a large amount of memory. Swap is designed as virtual memory, which uses your harddrive to store data that cannot be held in RAM. This tutorial will show you how to create a swap file, which should work under Ubuntu, CentOS, and Debian. This tutorial is not meant for any Custom ISO, but it is possible to follow along.

How to Setup Creat Swap on Linux on VULTR VPS

How to Setup Creat Swap on Linux on VULTR VPS

Step 1: Verify that swap does not exist

To prevent any issues during this tutorial, you will need to run the following to verify that a swap space is currently not active:

After running that command you should see something similar to this output:

If you see a value of 0 in the Swap section, then you can proceed to step 2.

Alternatively, you can run the following command to see if there is a configured swap file:

If you do not see any output from swapon, then proceed to step 2.

Step 2: Create swap file

You will need to choose a location for your file. In this tutorial, it will be stored at the root of the server. We will create a 2GB swap file by running the following command:

The dd command will produce output in a similar format to:

Next, verify that the file is located at the root of your Vultr VPS by running:

Proceed if you see the swapfile file.

Step 3: Activate the swap file

Swap files are not recognized automatically. We will need to tell the server how to format the file and enable it so it can be used as a valid swap file. As a security measure, update the swapfile permissions to only allow R/W for root and no other users. Run:

The permission change can be verified by running the following command:

You will see a file display:

Next, tell the server to setup the swap file by running:

After running it, you will see the following output:

If everything is shown as above, you are now ready to move on to the next step.

Step 4: Turn swap on

Once your file is ready to be used as swap, you need to enable it by running:

You can verify that the swap file is active by running the free command again.

If Swap shows something other than 0, then you have successfully setup swap.

Step 5: Enable swap on reboot

By default, your server will not automatically enable this new swap file. To enable it on boot, you can update the /etc/fstab file. Any text editor will suffice. In this example, I will be using nano.

Add the following line at the end of the file:

Save and close when you are finished editing the file. We are all done!