BASH

Check and Restart Web Service if Down

Create a robust Bash script to periodically check the status of a web service (e.g., Nginx, Apache) and automatically restart it if it's not running.

#!/bin/bash
SERVICE_NAME="nginx"
LOG_FILE="/var/log/service_monitor.log"

# Function to log messages
log_message() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

log_message "Checking status of $SERVICE_NAME..."

if systemctl is-active --quiet "$SERVICE_NAME"; then
    log_message "$SERVICE_NAME is running."
else
    log_message "$SERVICE_NAME is not running. Attempting to restart..."
    systemctl start "$SERVICE_NAME"
    if [ $? -eq 0 ]; then
        log_message "$SERVICE_NAME restarted successfully."
    else
        log_message "Failed to restart $SERVICE_NAME."
        # Optionally, send an alert here
        # echo "Alert: $SERVICE_NAME failed to restart!" | mail -s "Service Alert" [email protected]
        exit 1
    fi
fi
How it works: This script monitors a specified system service (e.g., `nginx`). It uses `systemctl is-active --quiet` to check if the service is currently running. If the service is found to be inactive, the script attempts to start it and logs the outcome. This is an essential script for cron jobs to ensure critical web services remain online and can be extended with alerting functionality for immediate notifications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs