Script to restart web service


Here is the simple bash script that checks if a website is running on a Linux or Bitnami server and restarts the web service if it’s not.

#!/bin/bash

WEBSITE_URL="http://example.com"
WEBSITE_STATUS=$(curl -IsS ${WEBSITE_URL} | head -n 1 | cut -d " " -f2)

if [ "${WEBSITE_STATUS}" != "200" ]; then
    echo "Website is not responding. Restarting web service..."
    sudo /opt/bitnami/ctlscript.sh restart apache   // this fro bitnami

    sudo service apache2 restart    / this is for Linux running with Apache2
    sleep 10 # Give some time for the service to restart
    NEW_WEBSITE_STATUS=$(curl -IsS ${WEBSITE_URL} | head -n 1 | cut -d " " -f2)
    if [ "${NEW_WEBSITE_STATUS}" = "200" ]; then
        echo "Web service restarted successfully."
    else
        echo "Failed to restart web service. Please check manually."
    fi
else
    echo "Website is running normally."
fi

Here’s what the script does:

  1. Defines the URL of the website to check (WEBSITE_URL).
  2. Uses curl to send a HEAD request to the website and captures the HTTP status code (200 for OK).
  3. If the status code is not 200, it assumes the website is not responding and restarts the Apache web service using the Bitnami control script.
  4. After restarting the service, it waits for 10 seconds to allow time for the service to start.
  5. Checks the website status again. If it returns a 200 status code, it confirms that the web service has restarted successfully.
  6. If the website still doesn’t respond after restarting the service, it prints a failure message.

Make sure to replace “http://example.com” with the actual URL of your website. Also, ensure that the path to the Bitnami control script (/opt/bitnami/ctlscript.sh) is correct for your installation.

Save this script to a file (e.g., check_website.sh), make it executable (chmod +x check_website.sh), and then you can schedule it to run periodically using cron or any other scheduling tool you prefer. For example, you can run it every 5 minutes by adding the following line to your crontab:

*/5 * * * * /path/to/check_website.sh

Replace /path/to/check_website.sh with the actual path to your script.

Leave a Reply

Your email address will not be published. Required fields are marked *