How to Monitor MySQL, Apache, and Nginx Uptime with Bash

Server stability depends on your core services staying up. If MySQL crashes or Nginx stops responding, your users will know before you do—unless you have monitoring in place.

In this guide, we will create a bash script to check the status of services like mysql, apache2, nginx, or docker and notify you immediately via AlertHub if they are down.

The Watchdog Script

We will create a script named check_services.sh. It will iterate through a list of services and check their status using systemctl.

Tip: This script uses the alerthub_alert function from our Bash Webhook Guide. Make sure it’s set up!

  1. Create the file:
nano ~/check_services.sh
  1. Paste the following content:
#!/bin/bash

# Configuration
# List the services you want to monitor, separated by spaces
SERVICES=("mysql" "nginx" "ssh")

# Source AlertHub function
if [ -f ~/.bashrc ]; then
    source ~/.bashrc
fi

# Function to check a single service
check_service() {
    local service=$1
    
    if systemctl is-active --quiet "$service"; then
        echo "✅ $service is running"
    else
        echo "❌ $service is DOWN"
        
        # Send Alert
        # We use a unique title per service to group alerts effectively
        alerthub_alert -t "$service is DOWN on $(hostname)" \
                       -d "The service '$service' has stopped running. Attempting to restart is recommended." \
                       -l "critical"
    fi
}

# Loop through all defined services
for service in "${SERVICES[@]}"; do
    check_service "$service"
done

Note: If you don’t use alerthub_alert, you can replace that line with the raw curl command shown in our Disk Usage guide.

Customizing for Your Stack

You can modify the SERVICES array to include whatever you run.

  • LAMP Stack: SERVICES=("apache2" "mysql")
  • LEMP Stack: SERVICES=("nginx" "mariadb" "php8.1-fpm")
  • Docker Host: SERVICES=("docker" "containerd")

Auto-Restarting (Optional)

You can take this script further by attempting to restart the service automatically before alerting:

if ! systemctl is-active --quiet "$service"; then
    echo "Attempting restart for $service..."
    sudo systemctl start "$service"
    sleep 5
    
    if ! systemctl is-active --quiet "$service"; then
        alerthub_alert -t "$service FAILED to Recover" -l "critical" -d "Service could not be restarted automatically."
    else
        alerthub_alert -t "$service Restarted" -l "warning" -d "Service crashed but was successfully restarted."
    fi
fi

Scheduling

Just like our disk monitor, we want this to run frequently. For service uptime, checking every 5 minutes is standard.

Add this to your crontab (crontab -e):

*/5 * * * * /home/your_user/check_services.sh

Conclusion

With this script, you are no longer flying blind. Whether it’s a database crash or a web server failure, AlertHub ensures you are the first to know, giving you the chance to fix it before customers start complaining.