BASH

Monitor and Restart a Systemd Service if Down

Create a bash script to periodically check the status of a critical systemd service (e.g., Nginx, PHP-FPM) and automatically restart it if it's found to be inactive.

#!/bin/bash

SERVICE_NAME="nginx"

# Check if the service is active
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "$(date): $SERVICE_NAME is running."
else
    echo "$(date): $SERVICE_NAME is not running. Attempting to restart..."
    sudo systemctl restart "$SERVICE_NAME"
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        echo "$(date): $SERVICE_NAME restarted successfully."
    else
        echo "$(date): Failed to restart $SERVICE_NAME. Manual intervention required."
        # Optionally send an email alert here
        # echo "Service $SERVICE_NAME failed to restart!" | mail -s "Service Alert" [email protected]
    fi
fi
How it works: This script provides basic service health monitoring for systemd-managed services. It checks if a specified service (e.g., `nginx`, `php-fpm`) is active using `systemctl is-active --quiet`. If the service is found to be inactive, it attempts to restart it using `sudo systemctl restart`. It then re-checks the service's status to confirm a successful restart or logs a failure, making it suitable for periodic execution via cron.

Need help integrating this into your project?

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

Hire DigitalCodeLabs