#selfhosting #wordpress or some other domain? … okay, then you need to make sure that your server stays running and that uptime is maximized. Let’s create two simple shell scripts that check the status of the apache2 web server, and restart that service if needed. First, create apache-notify.sh:
sudo touch /usr/local/bin/apache-notify.sh
sudo chmod 750 /usr/local/bin/apache-notify.sh
sudo chown $USER:$USER /usr/local/bin/apache-notify.sh
sudo nano /usr/local/bin/apache-notify.sh
Ok, now that we created the first script file and made it executable, paste in the contents below but adjust them to your needs.
#!/bin/sh
#functions
RESTART=”/bin/systemctl restart apache2.service”
SERVICE=”apache2.service”
LOGFILE=”/home/username/Desktop/apache-restart.log”
#check for the word dead in the service output from systemctl
if
systemctl status apache2.service | grep dead
then
echo “Sir, apache2 failed at $(date), so I restarted it for you.” >> $LOGFILE
else
echo “Ms., apache2 was running as of $(date)” >> $LOGFILE
fi
Ok, now we also want to restart it at exactly the same time that we found out it wasn’t running. So, you can also create a script called apache-restart.sh that restarts the service when it finds it dead:
sudo touch /usr/local/bin/apache-restart.sh
sudo chmod 750 /usr/local/bin/apache-restart.sh
sudo chown $USER:$USER /usr/local/bin/apache-restart.sh
sudo nano /usr/local/bin/apache-restart.sh
Ok, now that we created the second script file and made it executable, paste in the contents below but adjust them to your needs.
#!/bin/sh
#functions
RESTART=”/bin/systemctl restart apache2.service”
SERVICE=”apache2.service”
LOGFILE=”/home/username/Desktop/apache-restart.log”
#check for the word dead in the service output from systemctl
if
systemctl status apache2.service | grep dead
then
$RESTART >> $LOGFILE
fi
Thanks to @varange on a Digital Ocean forum who inspired these scripts, but I had to change them for systemd, and I also changed them into two scripts because the way he had originally composed them together with an “else” comment, there was always a minute discrepancy between the notification it was down, and the time it restarted. I would love to re-combine this into one script that does both, but for now this works. Comments welcome for those who can combine. Lastly, these will not run automatically, so create a cron job:
sudo crontab -e
* * * * * /bin/bash /usr/local/bin/apache-notify.sh
* * * * * /bin/bash /usr/local/bin/apache-restart.sh
sudo systemctl stop apache2
sudo systemctl restart cron
sudo systemctl status apache2 [Wait 1 minute, and then run again]
Make sure to run the cron job as root, or it will not work. You can also run the scripts manually if you want since we added them to the default user PATH above. This post is part of an extension I just added to a larger tutorial Apache Survival, a self-hosting beginner guide.