BASH

Graceful Web Service Restart with Config Check

Safely restart or reload common web services like Nginx, Apache, or PHP-FPM after configuration changes, including a syntax check before reloading to prevent downtime.

#!/bin/bash

# Usage: ./restart_service.sh nginx
# Usage: ./restart_service.sh php-fpm
# Usage: ./restart_service.sh apache2

SERVICE_NAME="$1"

if [ -z "$SERVICE_NAME" ]; then
    echo "Error: Service name not specified."
    echo "Usage: $0 <service_name>"
    echo "Supported services: nginx, apache2, php-fpm, systemd-daemon"
    exit 1
fi

echo "Attempting to restart/reload service: $SERVICE_NAME"

case "$SERVICE_NAME" in
    nginx)
        echo "Checking Nginx configuration syntax..."
        sudo nginx -t
        if [ $? -eq 0 ]; then
            echo "Nginx configuration syntax is OK. Reloading Nginx..."
            sudo systemctl reload nginx
            echo "Nginx reloaded."
        else
            echo "Nginx configuration syntax error. Aborting reload."
            exit 1
        fi
        ;;
    apache2)
        echo "Checking Apache configuration syntax..."
        sudo apache2ctl configtest
        if [ $? -eq 0 ]; then
            echo "Apache configuration syntax is OK. Reloading Apache..."
            sudo systemctl reload apache2
            echo "Apache reloaded."
        else
            echo "Apache configuration syntax error. Aborting reload."
            exit 1
        fi
        ;;
    php-fpm)
        echo "Reloading PHP-FPM service (e.g., php7.4-fpm, php8.0-fpm)..."
        # This assumes your PHP-FPM service name is php-fpm (e.g., on some systems)
        # or it might be version specific like php7.4-fpm, php8.1-fpm
        # Adjust the service name below if necessary for your system.
        # Example: sudo systemctl reload php8.1-fpm
        sudo systemctl reload $(sudo systemctl list-units --type=service --all | grep -o 'php[0-9]\.[0-9]-fpm.service' | head -n 1 | sed 's/\.service$//') || \
        sudo systemctl reload php-fpm
        if [ $? -eq 0 ]; then
            echo "PHP-FPM reloaded."
        else
            echo "Failed to reload PHP-FPM. Check service name or logs."
            exit 1
        fi
        ;;
    *)
        echo "Error: Unsupported service '$SERVICE_NAME'. Add support for it or use systemctl directly."
        exit 1
        ;;
esac
How it works: This script provides a safer way to restart or reload critical web services like Nginx, Apache, or PHP-FPM. Before attempting a reload, it performs a syntax check on the service's configuration. If the syntax is valid, it proceeds with a `systemctl reload` command, minimizing downtime. If an error is found, it aborts, preventing potential service outages due to bad configurations. It includes logic to auto-detect common PHP-FPM service names.

Need help integrating this into your project?

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

Hire DigitalCodeLabs