BASH
Monitoring and Auto-Restarting a Web Service in Bash
Create a bash script to continuously monitor the status of a specific web service and automatically restart it if it's found to be inactive or crashed.
#!/bin/bash
SERVICE_NAME="apache2" # Change to your web service, e.g., 'nginx', 'httpd'
LOG_FILE="/var/log/${SERVICE_NAME}_monitor.log"
CHECK_INTERVAL=30 # Check every 30 seconds
# Ensure log file directory exists
mkdir -p "$(dirname "$LOG_FILE")"
touch "$LOG_FILE"
echo "$(date): Starting service monitor for $SERVICE_NAME..." >> "$LOG_FILE"
while true; do
TIMESTAMP=$(date +%Y-%m-%d_%H:%M:%S)
# Check if the service is active using systemctl
# systemctl is-active --quiet returns 0 if active, non-zero otherwise
if systemctl is-active --quiet "$SERVICE_NAME"; then
echo "$TIMESTAMP: $SERVICE_NAME is active." >> "$LOG_FILE"
else
echo "$TIMESTAMP: $SERVICE_NAME is NOT active. Attempting to restart..." >> "$LOG_FILE"
# Attempt to restart the service
systemctl restart "$SERVICE_NAME"
# Give it a moment and check again
sleep 5
if systemctl is-active --quiet "$SERVICE_NAME"; then
echo "$TIMESTAMP: $SERVICE_NAME restarted successfully." >> "$LOG_FILE"
else
echo "$TIMESTAMP: ERROR: $SERVICE_NAME failed to restart. Manual intervention required." >> "$LOG_FILE"
fi
fi
sleep "$CHECK_INTERVAL"
done
How it works: This script continuously monitors a specified systemd service (e.g., `apache2` or `nginx`). It checks the service status using `systemctl is-active` at a defined interval. If the service is found to be inactive, it attempts to restart it and logs all actions with timestamps to a dedicated log file, providing basic error recovery for critical web services.