BASH
Automate Web Server Reload on Configuration File Changes
Automatically monitor web server configuration files (Nginx or Apache) for changes and gracefully reload the service to apply updates without downtime.
#!/bin/bash
# Configuration
CONFIG_DIR="/etc/nginx/sites-enabled/" # Or /etc/apache2/sites-enabled/
SERVICE_NAME="nginx" # Or apache2
# Check if inotifywait is installed
if ! command -v inotifywait &> /dev/null
then
echo "inotifywait could not be found. Please install inotify-tools (e.g., sudo apt install inotify-tools)."
exit 1
fi
echo "Monitoring $CONFIG_DIR for changes. Press Ctrl+C to stop."
# Loop indefinitely, watching for file changes
while true; do
# Wait for any file event (create, modify, delete) in the config directory
inotifywait -e create -e modify -e delete -e move "$CONFIG_DIR" 2>/dev/null
# A change was detected, attempt to reload the service
echo "Configuration change detected. Reloading $SERVICE_NAME..."
sudo systemctl reload "$SERVICE_NAME"
if [ $? -eq 0 ]; then
echo "$SERVICE_NAME reloaded successfully."
else
echo "Failed to reload $SERVICE_NAME. Check logs for errors."
fi
done
How it works: This script leverages `inotifywait` (part of the `inotify-tools` package) to continuously monitor a specified directory for any file changes. When a file is created, modified, deleted, or moved within the configured directory (e.g., your Nginx or Apache site configurations), it triggers a graceful reload of the web server service using `systemctl reload`. This ensures that configuration updates are applied automatically and quickly without needing manual intervention or service restarts, minimizing downtime.