BASH
Monitor and Restart a Web Service
Create a bash script to periodically check if a critical web service (e.g., Nginx, Apache) is running and automatically restart it if it's down, ensuring continuous uptime.
#!/bin/bash
# Configuration variables
SERVICE_NAME="nginx" # Name of the service to monitor (e.g., 'apache2', 'httpd', 'mysql')
LOG_FILE="/var/log/${SERVICE_NAME}_monitor.log" # Log file for monitoring actions
# Ensure the log file exists and is writable
mkdir -p "$(dirname "$LOG_FILE")"
touch "$LOG_FILE"
# Check if the service is active using systemctl
# --quiet suppresses output, -eq 0 means active
if ! systemctl is-active --quiet "$SERVICE_NAME"; then
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $SERVICE_NAME is down. Attempting to restart..." | tee -a "$LOG_FILE"
systemctl restart "$SERVICE_NAME" >> "$LOG_FILE" 2>&1
# Check status again after restart attempt
if systemctl is-active --quiet "$SERVICE_NAME"; then
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $SERVICE_NAME restarted successfully." | tee -a "$LOG_FILE"
else
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Failed to restart $SERVICE_NAME. Manual intervention required." | tee -a "$LOG_FILE"
fi
else
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $SERVICE_NAME is running." | tee -a "$LOG_FILE"
fi
How it works: This script monitors the status of a specified system service (e.g., 'nginx', 'apache2') critical for a web application. If the service is detected as inactive, it automatically attempts to restart it. All actions, including timestamps and outcomes, are logged to a dedicated file, helping maintain server uptime and providing a clear audit trail for service health.