BASH
Monitor Web Service Health with HTTP Status
Create a bash script to periodically check the HTTP status code of a web service endpoint and report if it's down or returning error codes (e.g., 4xx, 5xx).
#!/bin/bash
# Configuration Variables
URL="https://your-website.com/health"
EXPECTED_STATUS="200"
LOG_FILE="/var/log/health_check.log"
NOTIFICATION_EMAIL="[email protected]" # Optional: set to empty string to disable email
# Function to send email notification
send_notification() {
if [ -n "$NOTIFICATION_EMAIL" ]; then
SUBJECT="Web Service Alert: $URL is DOWN or ERRORS!"
MESSAGE="Service URL: $URL
Timestamp: $(date)
Status Code: $1
Details: $2"
echo -e "$MESSAGE" | mail -s "$SUBJECT" "$NOTIFICATION_EMAIL"
echo "Email notification sent to $NOTIFICATION_EMAIL"
fi
}
# Check HTTP status code using curl
HTTP_STATUS=$(curl -o /dev/null -s -w "%{http_code}
" "$URL")
TIMESTAMP=$(date +%Y-%m-%d_%H:%M:%S)
if [ "$HTTP_STATUS" -eq "$EXPECTED_STATUS" ]; then
echo "[$TIMESTAMP] INFO: $URL is UP. Status: $HTTP_STATUS" | tee -a "$LOG_FILE"
else
echo "[$TIMESTAMP] ALERT: $URL is DOWN or ERRORS! Status: $HTTP_STATUS" | tee -a "$LOG_FILE"
send_notification "$HTTP_STATUS" "Unexpected HTTP status code received."
fi
How it works: This bash script serves as a basic health monitor for a web service. It uses `curl` to fetch the HTTP status code of a specified URL without downloading the response body (`-o /dev/null -s -w "%{http_code}
"`). The script compares the retrieved status code with an `EXPECTED_STATUS` (e.g., 200 for success). If the status code doesn't match, it logs an alert message to a specified `LOG_FILE` and can optionally send an email notification using the `mail` command. This script is ideal for scheduling with cron to regularly check the availability and responsiveness of your web applications.