Restart Apache automatically in Ubuntu 20.04

There are times when Apache may crash for different reasons. In this article we will explore how to restart Apache automatically in Ubuntu 20.04 via a bash script if it’s inactive.

Bash is a powerful tool and we can do many things with it. In the following script we will 1st find out if Apache is running or dead/inactive. If it’s status is inactive, the script will attempt to restart it if there are no major bug in it which may block restarting it.

Create a directory apache in /opt, create a bash file(httpd.sh) with either touch or just vim.

vim /opt/apache/httpd.sh

Paste the following in it:

#!/bin/sh

START_APACHE="systemctl start apache2"
LOGS="/opt/apache/autostart-apache2.log"

if systemctl status apache2 | grep -q inactive
then
	echo "====== $(date) ======" >> $LOGS
	echo "Starting Apache..." >> $LOGS
	$START_APACHE >> $LOGS
	if systemctl status apache2 | grep -q active
	then
		echo "Apache started successfully" >> $LOGS
	fi
	echo "================================" >> $LOGS
else
	echo "====== $(date) ======"
	echo "Apache is running"
	echo "================================"
fi

The script is straight forward, it checks for Apache status and then start it if it’s dead. Log the messages where necessary. The inactive status messages are not piped to a log file to avoid spamming the logs.

Final step is to create a cronjob as root.

crontab -e

Paste the following in it:

* * * * * sh /opt/apache/httpd.sh