BASH

Gracefully Restart a Web Service and Check Status

A robust bash script to gracefully restart common web services (e.g., Nginx, Apache, PHP-FPM) and verify their running status, minimizing downtime during deployments or configuration changes.

#!/bin/bash

SERVICE_NAME="nginx" # Change to 'apache2', 'httpd', 'php-fpm', etc.

echo "Attempting to gracefully restart $SERVICE_NAME..."

# Check if systemctl is available (for modern Linux systems)
if command -v systemctl &> /dev/null; then
  sudo systemctl restart "$SERVICE_NAME"
  if [ $? -eq 0 ]; then
    echo "$SERVICE_NAME restarted successfully. Checking status..."
    sudo systemctl status "$SERVICE_NAME" --no-pager | head -n 3
  else
    echo "Error: Failed to restart $SERVICE_NAME using systemctl." >&2
    exit 1
  fi
# Fallback to 'service' command (for older systems or specific configurations)
elif command -v service &> /dev/null; then
  sudo service "$SERVICE_NAME" restart
  if [ $? -eq 0 ]; then
    echo "$SERVICE_NAME restarted successfully. Checking status..."
    sudo service "$SERVICE_NAME" status | head -n 3
  else
    echo "Error: Failed to restart $SERVICE_NAME using service." >&2
    exit 1
  fi
else
  echo "Error: Neither 'systemctl' nor 'service' command found. Cannot manage service." >&2
  exit 1
fi
How it works: This script provides a safe way to restart a specified web service (`nginx`, `apache2`, `php-fpm`, etc.). It first checks for the presence of `systemctl` (for Systemd-based systems) and attempts a restart. If `systemctl` is not found, it falls back to the `service` command. After the restart attempt, it verifies the command's exit status and then displays a truncated status output to confirm the service is running. This minimizes downtime by ensuring the service comes back online correctly after updates or configuration changes during web deployments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs