← Back to all snippets
BASH

Monitor and Auto-Restart a Critical Web Service

Implement a bash script to periodically check if a critical web service (e.g., a Node.js app, Gunicorn) is running and automatically restart it if it's found to be down.

#!/bin/bash

# Configuration
SERVICE_NAME="node_app.js" # Or "gunicorn" or specific process name
SERVICE_PATH="/path/to/your/app/index.js"
LOG_FILE="/var/log/my_service_monitor.log"

# Function to start the service
start_service() {
    echo "$(date): Attempting to start $SERVICE_NAME..." | tee -a "$LOG_FILE"
    # Example: node.js app
    nohup node "$SERVICE_PATH" > /dev/null 2>&1 & 
    # Example: Python Gunicorn app
    # nohup gunicorn my_app:app -b 0.0.0.0:8000 > /dev/null 2>&1 & 

    # Give it a moment to start
    sleep 5
    if pgrep -f "$SERVICE_NAME" > /dev/null; then
        echo "$(date): $SERVICE_NAME started successfully." | tee -a "$LOG_FILE"
    else
        echo "$(date): Failed to start $SERVICE_NAME." | tee -a "$LOG_FILE"
    fi
}

# Check if service is running
if pgrep -f "$SERVICE_NAME" > /dev/null; then
    echo "$(date): $SERVICE_NAME is running." | tee -a "$LOG_FILE"
else
    echo "$(date): $SERVICE_NAME is NOT running. Restarting..." | tee -a "$LOG_FILE"
    start_service
fi
How it works: This script periodically checks for the presence of a specified web service process using `pgrep`. If the service is not found, it attempts to restart it. The script uses `nohup` and `&` to run the service in the background, detaching it from the current shell. Output is logged to a specified file, providing a history of service status and restarts. This script is commonly scheduled via `cron` to ensure high availability of web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs