← Back to all snippets
BASH

Monitor and Auto-Restart Systemd Service

A robust bash script to check the status of a systemd service (e.g., Nginx, Apache) and automatically restart it if it's inactive or failed, ensuring service uptime.

#!/bin/bash

SERVICE_NAME="nginx" # Replace with your service name (e.g., apache2, postgresql)
LOG_FILE="/var/log/service_monitor.log"

# Ensure log file exists
mkdir -p "$(dirname "$LOG_FILE")"
touch "$LOG_FILE"

echo "$(date +"%Y-%m-%d %H:%M:%S") - Checking service: $SERVICE_NAME" >> "$LOG_FILE"

if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "$(date +"%Y-%m-%d %H:%M:%S") - Service '$SERVICE_NAME' is running." >> "$LOG_FILE"
elif systemctl is-failed --quiet "$SERVICE_NAME"; then
    echo "$(date +"%Y-%m-%d %H:%M:%S") - Service '$SERVICE_NAME' is in a failed state. Attempting to restart..." >> "$LOG_FILE"
    sudo systemctl restart "$SERVICE_NAME"
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        echo "$(date +"%Y-%m-%d %H:%M:%S") - Service '$SERVICE_NAME' restarted successfully." >> "$LOG_FILE"
    else
        echo "$(date +"%Y-%m-%d %H:%M:%S") - Failed to restart service '$SERVICE_NAME'." >> "$LOG_FILE"
    fi
else
    echo "$(date +"%Y-%m-%d %H:%M:%S") - Service '$SERVICE_NAME' is not active. Attempting to start..." >> "$LOG_FILE"
    sudo systemctl start "$SERVICE_NAME"
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        echo "$(date +"%Y-%m-%d %H:%M:%S") - Service '$SERVICE_NAME' started successfully." >> "$LOG_FILE"
    else
        echo "$(date +"%Y-%m-%d %H:%M:%S") - Failed to start service '$SERVICE_NAME'." >> "$LOG_FILE"
    fi
fi
How it works: This script monitors a specified systemd service. It first checks if the service is active or failed using `systemctl`. If it's not active or is in a failed state, the script attempts to restart or start the service using `sudo systemctl`. All actions and timestamps are logged to a specified file, making it easy to track service status and ensuring continuous operation for critical web services.

Need help integrating this into your project?

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

Hire DigitalCodeLabs