Recently I tried installing WordPress on a VPS with 512 MB RAM running Ubuntu 18.04. With this low amount of RAM, MySQL kept crashing. I quickly noticed that the server did not have swapping enabled which would have helped in preventing the service from crashing.
If you face similar issues you should check if swapping is enabled on your server. Run the below command and if the output is blank it means that swapping is not enabled.
sudo swapon --show
For those who don’t know what swapping is, when the operating system runs out of RAM and if swapping is enabled, then the operating system can temporarily move some data from RAM onto the hard disk, thus freeing some space for other processes. Well, if this one line explanation is not good enough for you then Google is your friend.
To enable swapping you either need to create a swap partition or a swap file. Creating a swap file is easy which I did using the below commands.
sudo fallocate -l 1G /swapfile sudo chmod 600 /swapfile
The first command creates a file named swapfile of size 1 GB in the root directory. The second command ensures that this file can only be accessed by root as we don’t want normal users to access this. Forgetting to set these permissions is a security risk!
Next we need to tell the operating system to use this swap file. You can do this by running the below command.
sudo swapon /swapfile
However, note that on restarting the server, swapping will be disabled again. To make this change permanent you need to add the below line to /etc/fstab.
/swapfile none swap sw 0 0
Too much swapping is not good as it reduces the performance. There is a swappiness setting which tells the operating system how often it should use the swap space. The value for this setting ranges from 0 to 100 where lower values mean avoid swapping often and higher values mean use swapping often.
You can check what the current value for swappiness is by running the below.
In my case this was 60, which I reduced to 10 by editing /etc/sysctl.conf to add the below line.
After these changes I rebooted the server and ensured that swapping is enabled and swappiness value is 10.
sudo reboot sudo swapon --show cat /proc/sys/vm/swappiness
MySQL on my server hasn’t crashed yet after making these changes!