BASH

Check and Restart Web Service

Automate checking if a critical web service (e.g., Nginx, PHP-FPM) is running and restart it if inactive, ensuring continuous availability for your web applications.

#!/bin/bash

SERVICE_NAME="nginx" # Specify the service to monitor (e.g., "nginx", "apache2", "php7.4-fpm", "mysql")

# Optional: Email for alerts if service is down and cannot restart
ALERT_EMAIL="[email protected]"

echo "Checking status of service: $SERVICE_NAME..."

# Check if the service is active using systemctl
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "$SERVICE_NAME is running."
else
    echo "$SERVICE_NAME is not running. Attempting to restart..."
    sudo systemctl restart "$SERVICE_NAME"
    
    # Check if restart was successful
    if [ $? -eq 0 ]; then
        echo "$SERVICE_NAME restarted successfully."
    else
        MESSAGE="Critical: Failed to restart $SERVICE_NAME on $(hostname). Please investigate."
        echo "$MESSAGE" >&2
        # Optionally send an email alert
        echo "$MESSAGE" | mail -s "Service Alert: $SERVICE_NAME down" "$ALERT_EMAIL"
        exit 1
    fi
fi

echo "Service check completed."
How it works: This script checks the status of a specified system service, such as a web server (Nginx, Apache) or an application server (PHP-FPM), using `systemctl`. If the service is not active, it attempts to restart it. This automation helps ensure the continuous availability of critical web application components, and can optionally send an email alert if the restart fails, prompting immediate human intervention.

Need help integrating this into your project?

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

Hire DigitalCodeLabs