Being a Linux and Cloud Engineer I happen to work on building many servers which should be reliable, and I come across few customers who just want the server to be build and least work in managing them. So, I came up to a solution to start services by themselves if the apache web server goes down using cron and if loop. The following script serves the purpose.
First let’s create a directory to put all the custom scripts to be put in there.
mkdir /scripts/ cd /scripts/
Let’s create a script and call it as apachechk.sh
touch apachechk.sh
Provide it with execution permission.
chmod +x apachechk.sh
Then let’s add the following entry to our root user’s cron
crontab -e */5 * * * * /scripts/apachechk.sh >/dev/null 2>&1
Now, let’s paste the following lines to the script file on our Debian/Ubuntu based system.
#!/bin/bash #This script will check if Apache process is down in Debian/Ubuntu based system and restarts it automatically. #Script is located at https://helpinlinux.com/shell-script-to-auto-restart-apache-httpd-when-it-goes-down-dead #Let's declare RESTART, PGREP and HTTPD command names. RESTART="service apache2 restart" PGREP="/usr/bin/pgrep" HTTPD="apache2" # find httpd pid $PGREP ${HTTPD} #Check if the process retruns not value[apache2 not running]. if [ $? -ne 0 ] then # restart apache $RESTART fi
If you are using CentOS/Redhat based system please add the following code to your apachechk.sh file.
#!/bin/bash #This script will check if Apache process is down in Redhat/CentOS based system and restarts it automatically. #Script is located at https://helpinlinux.com/shell-script-to-auto-restart-apache-httpd-when-it-goes-down-dead #Let's declare RESTART, PGREP and HTTPD command names. RESTART="service httpd restart" PGREP="/usr/bin/pgrep" HTTPD="httpd" # find httpd pid $PGREP ${HTTPD} #Check if the process retruns not value[httpd not running]. if [ $? -ne 0 ] then # restart apache $RESTART fi
Reference: http://bash.cyberciti.biz/web-server/restart-apache2-httpd-shell-script/
Leave a Comment