How to fix Mysql server stops very frequently

I have had a problem with my WordPress site, the connection with MySql have gone away and to get it back I had to restart the server. This been an annoying issue as I do not have that high traffic on the site.

I tried to check if mysql is up and make cronjob to restart it but that does not work that well.  I been looking at the log, using.

tail /var/log/mysql/error.log

In the log I looked for shutdown messages or errors. I identified that the mysql connection crashed when the server run out of memory, so why did it run out of memory. I started to optimize Mysql resources by using the optimization tool from Percona tools.

I also checked when my WordPress is running smoothly or what is causing heavy traffic peaks to your db. One way is to increase the size of the server, I did nto have that much traffic, so I installed the New Relic tool on my server to monitor the server resources to find out which process are consuming memory.

I found out that the server did not have enough memory and mysql can’t allocate what it needs so it crashes, what I did was to add swap space to help this.

On the command line

[email protected]:~# dd if=/dev/zero of=/swap.dat bs=1024 count=512k
[email protected]:~# mkswap /swap.dat
[email protected]:~# swapon /swap.dat
[email protected]:~# vim /etc/fstab

vim is started to edit, add the following to the end of /etc/fstab file

/swap.dat      none    swap    sw      0       0

Then, edit the mysql config file

[email protected]:~# vim /etc/mysql/my.cnf

And add this under [mysqld]


Finally, reload mysql

[email protected]:~#  service mysqld reload

From the New Relic account, I also noticed that the PHP was taken up memory, so I upgraded my server version of PHP from 5.5 to version 7. That helped my issue and after this changes to the server, I have not had an issue with MySql connection going away.