BASH

Monitor and Restart Web Services Automatically

Develop a Bash script to continuously monitor a specific web service or process by name, automatically restarting it if it's found to be inactive, ensuring high uptime.

#!/bin/bash

SERVICE_NAME="nginx"

# Function to check and restart services managed by systemd
check_and_restart_systemd() {
    if ! systemctl is-active --quiet "${SERVICE_NAME}"; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') - ${SERVICE_NAME} is not running. Attempting to restart..."
        sudo systemctl restart "${SERVICE_NAME}"
        if systemctl is-active --quiet "${SERVICE_NAME}"; then
            echo "$(date '+%Y-%m-%d %H:%M:%S') - ${SERVICE_NAME} restarted successfully."
        else
            echo "$(date '+%Y-%m-%d %H:%M:%S') - Failed to restart ${SERVICE_NAME}."
        fi
    else
        echo "$(date '+%Y-%m-%d %H:%M:%S') - ${SERVICE_NAME} is running."
    fi
}

# --- Main Logic (can be put in a loop or cron job) ---
check_and_restart_systemd

# To run this script continuously, you can use a while loop, e.g.:
# while true; do
#     check_and_restart_systemd
#     sleep 60 # Check every 60 seconds
# done
# Run in background with `nohup ./script.sh &`
How it works: This script provides a method to monitor a web service managed by systemd and automatically restart it if it goes down. The `check_and_restart_systemd` function uses `systemctl is-active --quiet` to check the service's status. If the service is inactive, the script attempts to restart it using `sudo systemctl restart` and logs the action. This script can be scheduled as a cron job or run in a continuous loop to ensure critical web services maintain high availability, minimizing downtime for 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