how-to-restart-mysql-server-after-Out-of-Memory

On default Digital Ocean WordPress installation, sometimes you may find following error while opening website:

Error establishing a database connection

Looking in the /var/log/syslog, we have:

May 3 08:08:13 myDigitalOceanDroplet kernel: [391622.639370] Out of memory: Killed process 98542 (mysqld) total-vm:165880kB, anon-rss:59772kB, file-rss:2396kB, shmem-rss:0kB, UID:112 pgtables:276kB oom_score_adj:0

It happens usually when the Wordpress is installed on the lowest droplet size, and not tuned properly. A large number of requests through Apache web server causes the memory to be exhaused and system automatically kills processes, to stay alive. As a fast workaround, you can monitor the MySQL process every minute and restart it if/when needed.

So, how you will do this ?

Save this script to /root/monitor-mysqld-process.sh:

#!/bin/sh

TEST=$(/usr/bin/pgrep -a mysqld | grep -v $0)
if [ -z "$TEST" ]; then
        DATE=$(date)
        echo "$DATE Restarting mysql service..."
        /usr/sbin/service mysql start
fi

Run this script from cron, every minute:

* * * * * /root/monitor-mysqld-process.sh >> /tmp/cron.monitor-mysqld-process.txt 2>&1

And finally, monitor temporary log:

tail -F /tmp/cron.monitor-mysqld-process.txt

Tue May  3 08:17:02 UTC 2022 Restarting mysql service...
All Articles Bookmarks