How to prevent your VPS from crashing!

This post is not complete click-bait, and will actually help you significantly decrease the amount of times your VPS crashes.


What this will fix

This will fix all crashes caused by low-memory situations. Linux will generally not crash directly from this, but when all RAM and swapspace is exhausted, it will invoke the OOM(out of memory) killer, which will attempt to kill the least processes to get the most free RAM and swap. This is most of the time a good thing, and will do something like kill the GUI in order to prevent a complete crash, which is what Windows tends to do. This does become problematic, however, when it begins to kill processes that are essential to the system’s stability.

What this fix will do

In this tutorial, I will show you how to install an application on Debian and Debian based distros that will create dynamic swap. What this means is that whenever your system is about to run out of swapspace and invoke the OOM killer, more swapspace will be added to prevent this. This will end up significantly slowing down your system, and if it’s a web server, your loading times will increase. It’s up to you to decide if a slow system is better than a crashed one. I would not recommend running this on a system that uses a HDD, as that is way to slow, especially when you start using multiple GB of swap. I also don’t recommend running any swap on a RAID 0 array, as if one bit on one of the drives fail, Linux will crash. That’s the only weakness I have found with Linux; if it’s swapspace is lost while in use, it will crash the system, and it’s not the developers’ fault, you’re in essence taking out RAM, but it’s just something to note.


Installing swapspace

This tutorial will only work if you use the “apt” tool to install packages. What we’re about to install should be in the default repositories and will not require adding one. Anyways, this is one of the easiest tutorials ever, so let’s get started!

All you need to run to install the utility is:

 sudo apt install swapspace

and press “Y” when prompted.

That’s it, you’re done! Now, onto creating a swapfile.

Creating the swap file

Note: This first way is faster, but not recommended.

sudo fallocate -l 1G /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

and swapspace should add more swap should the allocated amount not be sufficient. If “fallocate” doesn’t work, then use “dd”, which is slower, but works:

sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress 
sudo mkswap /swapfile
sudo swapon /swapfile

and you should be good.

One comment

  1. I have decided to just use a normal swapfile, and let the OOM killer do its job when the time comes. However, this is only because I have 512MB of RAM. If you have a few GB, then I recommend swapspace

Leave a Reply(Markdown is On)