How to Restart MySQL From Cron After it Suddenly Shuts Down

September 20th, 2007 at 11:03 pm

The MySQL server that WP Text Ads runs on (5.0.32-Debian_7etch1-log) has been shutting down by itself over the last few weeks. Up to today, I still don’t know why. The error log doesn’t say anything other than that MySQL shut down gracefully.

Downtime is really bad for WP Text Ads. So it is important that there’s a way to monitor the MySQL server and detect if it has shut down.

I found a wonderful script from Bash Shell Script Directory to do this. Made a few modifications to it and it has worked very well for me.

Here is the modified script. It restarts MySQL server if it is killed or not working for any reason. When the script detects MySQL is not running (by sending ping requests to MySQL), it tries to restart using /etc/init.d/mysql and sends an email to you indicating the status.

This script should be run as a cron job.

#!/bin/bash
#
# This script is licensed under GNU GPL version 2.0 or above
#

# mysql server hostname
MHOST="localhost"

#path to MySQL daemon start/stop script.
MSTART="/etc/init.d/mysql start"

# Email address to send notification
EMAILID="username@domain.com"

# path to mail program
MAILCMD="$(which mail)"

# path mysqladmin
MADMIN="$(which mysqladmin)"

MAILMESSAGE="/tmp/mysql.fail.$$"

# see if MySQL server is alive or not
$MADMIN --defaults-file=/etc/mysql/debian.cnf ping 2>/dev/null 1>/dev/null

if [ $? -ne 0 ]; then
        echo "" >$MAILMESSAGE
        echo "Error: MySQL Server is not running/responding ping request">>$MAIL
MESSAGE
        echo "Hostname: $(hostname)" >>$MAILMESSAGE
        echo "Date & Time: $(date)" >>$MAILMESSAGE
        # try to start mysql
        $MSTART>/dev/null
        # see if it is started or not
        o=$(ps cax | grep -c ' mysqld$')
        if [ $o -eq 1 ]; then
                sMess="MySQL Server MySQL server successfully restarted"
        else
                sMess="MySQL server FAILED to restart"
        fi
        # Email status too
        echo "Current Status: $sMess" >>$MAILMESSAGE
        echo "" >>$MAILMESSAGE
        echo "*** This email generated by $(basename $0) shell script ***" >>$MA
ILMESSAGE
        echo "*** Please don't reply this email, this is just notification email
 ***" >>$MAILMESSAGE
        # send email
        $MAILCMD -s "MySQL server" $EMAILID < $MAILMESSAGE
else # MySQL is running :) and do nothing
        :
fi
# remove file
rm -f $MAILMESSAGE

You need to save the above script as the ‘root’ user. Then edit your cron (as ‘root’) to run this script.

I make sure cron runs this script every 3 minutes (assuming I named this script check_mysql):

*/3 * * * * bash /root/check_mysql

I hope this tip helps anyone who’s facing the same unsolvable problem as me. :)

WP Text Ads Like this post? Buy an ad and drive visitors to your site

Related Posts:
  • No related posts

About the author

I'm Alex Choo and I live in sunny Singapore. I'm also the developer of WP Text Ads, a WordPress plugin that lets bloggers sell ads directly to advertisers so that they pay 0% in commissions and earn 100% in profits.

Feel free to drop me a note anytime you wish. You should also subscribe to the low volume email announcement list for WP Text Ads below.

Email address:

Comments 15

  1. Виталий wrote:

    Тут уже столько написали до меня. Мне осталось только присоединиться.

    Posted 25 Dec 2008 at 2:40 pm
  2. Beckham wrote:

    Отлично написано! Надобыотметить на ХабрХабр. :)

    Posted 27 Jan 2009 at 9:53 pm
  3. Вилор wrote:

    Большое спасибо за замечательную возможность оставлять комментарии на этой странице!

    Posted 02 Feb 2009 at 11:07 am
  4. petya wrote:

    Да, было бы смешно, если б к сожалению не было так грустно …

    Posted 03 Feb 2009 at 11:49 pm
  5. Арнольд wrote:

    Познавательно, а продолжение будет?

    Posted 04 Feb 2009 at 7:09 pm
  6. Ivan wrote:

    I can’t restart mysql safely

    Posted 11 Feb 2009 at 8:07 pm
  7. BakinskiyAvtos wrote:

    Да, интернет - огромен, если и такое можно найти ;)

    Posted 26 Feb 2009 at 6:51 am
  8. джaн wrote:

    Вот про все это я почитал с большим интересом. И с удовольствием прочитал бы еще больше! Планируете и дальше писать на эту же тему? Спасибо

    Posted 21 May 2009 at 12:09 am
  9. Семен Шишкин wrote:

    Блин… Реально красиво написано! Все это так знакомо…и правдиво!

    Posted 30 May 2009 at 12:29 pm
  10. интeллигeнт wrote:

    Отличный сайт! Если необходимо убить парочку-троечку часов - вам сюда :)

    Posted 04 Jul 2009 at 4:02 am
  11. Егор Макаров wrote:

    Я, хоть и не ваш постоянный читатель, но всё же выскажусь. На ваш сайт попал совсем случайно. Однако узнал много чего нового и интересного. Так что, как говорится, пиши еще :)

    Posted 24 Jul 2009 at 6:19 am
  12. Петр wrote:

    Зачет!:) Но есть и минус небольшой! У меня скорость инета 112 кбит/сек. Страница грузилась около 30 секунд.

    Posted 28 Oct 2009 at 6:51 am
  13. Артур Конев wrote:

    Да уж… Жизнь - как вождение велосипеда. Чтобы сохранить равновесие, ты должен двигаться.

    Posted 05 Nov 2009 at 6:57 pm
  14. Марианна Дементиевна wrote:

    спасибо… я действительно млею от вашего сайта или как ещё сказать… я весь день прожила тут… читаю и сохраняю в сердце.. думаю Вы не против…

    Posted 15 Nov 2009 at 6:15 am
  15. occusezoort wrote:

    C наступающим Вас! Пусть Ваши мечты сбудутся!

    Posted 01 Jan 2010 at 9:40 am

Post a Comment

Your email is never published nor shared. Required fields are marked *