BASH

Check and Restart a Linux Service by Name

Automate checking if a critical Linux service (e.g., Nginx, a Node.js process) is running and restart it if it's found to be inactive, ensuring application uptime.

#!/bin/bash
SERVICE_NAME="nginx" # Replace with your service name (e.g., apache2, myapp_worker)

# Check if the service is active using systemctl (for systemd-based systems)
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "$SERVICE_NAME is running."
else
    echo "$SERVICE_NAME is not running. Attempting to start..."
    sudo systemctl start "$SERVICE_NAME"
    if [ $? -eq 0 ]; then
        echo "$SERVICE_NAME started successfully."
    else
        echo "Failed to start $SERVICE_NAME."
        exit 1
    fi
fi

# Alternative for non-systemd systems or custom processes:
# Check if process is running by name (less robust than systemctl)
# if pgrep -x "$SERVICE_NAME" > /dev/null; then
#     echo "$SERVICE_NAME process is running."
# else
#     echo "$SERVICE_NAME process is NOT running. You might need to manually start it."
# fi
How it works: This script checks the status of a specified Linux service, such as a web server or a background worker, using `systemctl`. If the service is found to be inactive, the script attempts to start it and reports the outcome. This is crucial for maintaining the availability of web applications by automatically restarting failed services, complementing cron jobs for continuous uptime.

Need help integrating this into your project?

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

Hire DigitalCodeLabs