In this article, we will go over how to create a swap file. A swap file is useful in instances where your VPS does not have enough memory to perform the tasks or processes that are running. This can cause your server to start killing processes in order to free up some memory, some of which may be important such as a database or a web server!
A swap file can help you avoid these issues by utilizing hard drive space as virtual memory when regular memory is not immediately available.
Adding a Swap file on Ubuntu 14.04
We must first make sure that there is no current swap file in use. The easiest way to determine this is to run the following command:
The output will show us how much memory the system has and how much, if any, swap has been configured. In this case, the VPS has just been provisioned, and no swap has been configured.
In the next step, we will choose the amount of space to allocate to swap. This can be accomplished by the following command:
dd if=/dev/zero of=/swapfile bs=1024 count=2048k
In this example, we will create a 2GB swap file. There are 1024 megabytes in 1 gigabyte, so in order to achieve 2GB I will be using 2048k as the count.
NOTE: Do not forget to include the “k” at the end, otherwise you will actually be creating a 2 megabyte swap file! This is because the byte size is being multiplied by the amount specified in the count block.
You can verify that you created the correct size by the output. Here we see 2.1 GB so we can continue to the next step.
Now we must assign the swap file we just created to the operating system:
Enable the swap file and verify it is assigned:
The output of “free -m” should now show the amount you configured for swap.
Next, we need to configure the system to enable the swap file every time the server boots. Otherwise, you would need to manually enable it every time you reboot the server using the “swapon /swapfile” command.
To accomplish this we will need to edit the /etc/fstab file using a text editor of your choice.
Add the following line to the end of the file:
/swapfile none swap sw 0 0
Once this has been completed, save your changes and close the file.
That’s it! You now have a persistent swap file for your VPS.