Script Auto Restart Service หากตรวจพบว่าไม่ทำงาน

บางครั้ง Service ที่เราสั่งให้ทำงานบน Server เช่น httpd ของ Apache หรือ mysql ดันหยุดทำงานไปซะดื้อๆ ซึ่งเป็นผลจาก Service error เอง หรือเกิดโหลดสูงบน Server จน Service ค้างทำให้ระบบที่เราใช้งานมีปัญหาไม่สามารถทำงานได้อย่างปกติ เราสามารถแก้ไขปัญหานี้ได้โดยใช้ Script ตรวจสอบและ Restart service ขึ้นมาใหม่ครับ

#!/bin/bash
# Hostname
URL="http://google.com"

# MySQL
USER="da_admin"
PASSWD=$(grep "^passwd=" /usr/local/directadmin/conf/mysql.conf | cut -d= -f2)

# CMD
WORK="200"
NGINX=$(curl --write-out %{http_code} --silent --output /dev/null $URL)
HTTPD=$(curl --write-out %{http_code} --silent --output /dev/null $URL':8085')
mysql --user="${USER}" --password="${PASSWD}" -e exit 2>/dev/null
SQLSTATUS=`echo $?`

# Auto restart nginx
if [ $NGINX -ne $WORK ]; then
echo Nginx response code $NGINX
/etc/init.d/nginx restart
fi;

# Auto restart httpd
if [ $HTTPD -ne $WORK ]; then
echo Nginx response code $NGINX
/etc/init.d/httpd restart
fi;

if [ $SQLSTATUS -ne "0" ]; then
echo MySQL is down!
/usr/bin/killall mysqld
/etc/init.d/mysqld restart
fi;

หลังจากสร้าง Script แล้วก็สามารถนำไปใส่ให้ chmod +x แล้วนำไปใส่ crontab ตั้งเวลาให้ทำงานอัตโนมัติได้เลยครับ

Was this article helpful?

Related Articles