Apache Restart CentOS Script With Examples

Apache web server restart is easy but how would you do it automatically? Few days back, my apache server crashed and my website was down for almost 3 hours. I only find it out when I opened my website in browser. So I thought of writing a script which will check if my website is down at regular interval and if it’s down then apache restart command will be issued.

Apache Restart CentOS Script

I am using CentOS operating system but my script should work on other Unix servers too. To have apache restart script setup we need the following:

  1. A PHP script that will check if website is online and PHP is running fine.
  2. A shell script that will use above PHP to check if website is offline, in that case restart apache web server.
  3. Setting cron job to run at regular intervals.

PHP Script to check website status

Here is the PHP script I wrote to check my website status.

servercheck.php

This is a very simple script which returns 1 if the website is UP or 0 if it’s DOWN.

Apache restart script

Here is the shell script I wrote to call the above PHP.

apache_restart.sh

This apache restart script first calls the PHP to check website status. If the website is down then it restarts the apache server and again checks the status after 10 seconds. If it’s UP then it sends a mail to the given email ID so that we know how many times server has been restarted.

If restart fails, apache restart script sends a mail with an error message that means something is really wrong with the server.

Make sure to give the script execute permission using chmod command and execute it once to test it. Also, check the server restart command as it depends on your server operating system.

Setting Cron Job for Apache Restart Script

Just add below line in the crontab entry to run the above script every five minutes. Make sure to give the correct path from root.

The log file will contain the output of the last run of the script. Now we are all set with the script and you will get notified whenever your server has been restarted or it’s in error state via email.

Reference: Apache HTTPD

By admin

Leave a Reply

%d bloggers like this: