BASH

Monitor and Auto-Restart Web App Process

Create a Bash script to continuously monitor a specific web application process and automatically restart it if it's not running, ensuring service uptime.

#!/bin/bash

# Configuration
PROCESS_NAME="my_node_app.js" # Or "gunicorn" or "php-fpm" etc.
START_COMMAND="/usr/bin/node /opt/my_app/my_node_app.js &" # Command to start the app
LOG_FILE="/var/log/app_monitor.log"

# Check if the process is running
if ! pgrep -f "$PROCESS_NAME" > /dev/null
then
    echo "$(date): $PROCESS_NAME is not running. Attempting to restart..." | tee -a "$LOG_FILE"
    eval "$START_COMMAND"
    if pgrep -f "$PROCESS_NAME" > /dev/null
    then
        echo "$(date): $PROCESS_NAME restarted successfully." | tee -a "$LOG_FILE"
    else
        echo "$(date): Failed to restart $PROCESS_NAME." | tee -a "$LOG_FILE"
    fi
else
    echo "$(date): $PROCESS_NAME is running." | tee -a "$LOG_FILE"
fi
How it works: This script monitors a specific process, identified by `PROCESS_NAME` (e.g., a Node.js app, Gunicorn, PHP-FPM). If `pgrep` indicates the process is not running, the script attempts to start it using `START_COMMAND`. All actions are logged to a specified log file, making it ideal for use with `cron` for periodic checks to ensure continuous service availability.

Need help integrating this into your project?

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

Hire DigitalCodeLabs