BASH
Monitoring and Auto-Restarting a Web Service (e.g., Nginx)
Ensure continuous availability of critical web services like Nginx by scripting a bash monitor that periodically checks process status and automatically restarts it if found down.
#!/bin/bash
# Configuration
SERVICE_NAME="nginx"
# This assumes systemd. For other init systems, adjust accordingly (e.g., 'service nginx start')
RESTART_COMMAND="sudo systemctl restart ${SERVICE_NAME}"
LOG_FILE="/var/log/service_monitor.log"
# --- DO NOT EDIT BELOW THIS LINE ---
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
# Check if the service is running using pgrep
# pgrep returns 0 if process found, 1 if not.
if pgrep -x "${SERVICE_NAME}" > /dev/null
then
echo "[$TIMESTAMP] ${SERVICE_NAME} is running." | tee -a "${LOG_FILE}"
else
echo "[$TIMESTAMP] ${SERVICE_NAME} is NOT running. Attempting to restart..." | tee -a "${LOG_FILE}"
# Attempt to restart the service
${RESTART_COMMAND} &>> "${LOG_FILE}"
# Check if restart was successful
if pgrep -x "${SERVICE_NAME}" > /dev/null
then
echo "[$TIMESTAMP] ${SERVICE_NAME} restarted successfully." | tee -a "${LOG_FILE}"
else
echo "[$TIMESTAMP] Failed to restart ${SERVICE_NAME}. Manual intervention required." | tee -a "${LOG_FILE}"
fi
fi
How it works: This script acts as a basic service monitor. It's designed to be run periodically (e.g., via cron job). It checks if a specified service (like Nginx) is running by looking for its process ID using `pgrep -x`. If the service is not found, the script logs the event and attempts to restart it using a predefined command (e.g., `sudo systemctl restart`). It then verifies if the restart was successful. All actions are logged to a specified file, providing a history of service status and restart attempts, crucial for maintaining web server uptime.