Auto restart Apache/HTTPD if it Goes Down/Stops

Apache/HTTPD can stop at any time and you may not have the time to monitor your server all the time. Although monitoring tools exists but you may not have the time to check it all the time. There are many reasons for Apache/HTTPD to stop working and many can be fixed temporarily through a simple restart of the service so that you do not lose any traffic. In our case, we had a client whose Apache service used to stop randomly and the logs too weren’t giving any good information but a restart used to fix it. Auto restart of Apache saved us.

Here’s how you can implement this feature too…

Requirements

  • Linux Server
  • SSH Client (Putty Recommended)
  • Text Editor (nano recommended)
  • Basic Server Knowledge
  • 5 Minutes
  • A cup of coffee

Steps

1 – SSH into your server using an SSH client.

2 – Create a directory where we will put the cron scripts. Below is the command to do it.

mkdir /restartcrons/

3 – Create a cron script which will restart apache automatically if it goes down/stops apacherestart.sh and provide it with the necessary permissions.

touch /restartcrons/apacherestart.sh
chmod +x /restartcrons/apacherestart.sh

4 – Add cron entry for the script.

crontab -e
*/5 * * * * /restartcrons/apacherestart.sh >/dev/null 2>&1

5 – Now there are two different scripts for different Linux distros with similar architecture. Verify which is the right one for you and use it. Enter your apacherestart.sh using a text editor.

nano /restartcrons/apacherestart.sh

CentOS/Redhat Linux/CloudLinux/Similar Architecture

RESTART="service httpd restart"
PGREP="/usr/bin/pgrep"
HTTPD="httpd"
$PGREP ${HTTPD}
if [ $? -ne 0 ]
then
 $RESTART
fi

Ubuntu/Debian/OpenSuse

 

RESTART="service httpd restart"
PGREP="/usr/bin/pgrep"
HTTPD="httpd"
$PGREP ${HTTPD}
if [ $? -ne 0 ]
then
 
 $RESTART
fi

That’s it! Apache will now restart automatically if it goes down/stops

yoast seo premium free
%d bloggers like this: