Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bulletinmybeard/a853a51af514fcd5a844673e5e8ab30b to your computer and use it in GitHub Desktop.
Save bulletinmybeard/a853a51af514fcd5a844673e5e8ab30b to your computer and use it in GitHub Desktop.
Detect NGINX configuration changes, test them, and reload NGINX automatically

This bash script monitors directories and files for changes, runs nginx -t to test the configuration, and reloads NGINX by executing nginx -s reload. All actions are being logged in /var/log/monitor.log and /var/log/monitor-errors.log.

Prerequisites

inotify-tools -> https://github.com/inotify-tools/inotify-tools

The Script

#!/bin/bash

set -o pipefail

CONFIG_DIRS=(
    "/etc/nginx/conf.d"
)

DELAY_IN_SECONDS=5

reload_nginx() {
    echo "$(date) - Changes detected, waiting for more changes..." >> /var/log/monitor.log
    sleep $DELAY_IN_SECONDS
    echo "$(date) - Delay passed, checking NGINX configuration..." >> /var/log/monitor.log
    if nginx -t 2>> /var/log/monitor-errors.log; then
        nginx -s reload
        echo "$(date) - NGINX successfully reloaded." >> /var/log/monitor.log
    else
        echo "$(date) - NGINX configuration test failed, reload skipped." >> /var/log/monitor-errors.log
    fi
}

# PID of the last reload task.
last_pid=0

inotifywait -m -r -e modify,create,delete "${CONFIG_DIRS[@]}" --format '%w%f' |
    while IFS= read -r file; do
        # Kill the last reload task if it's still running
        if [ $last_pid -ne 0 ]; then
            kill $last_pid 2>/dev/null
        fi
        # Start a new reload task in the background
        reload_nginx &
        last_pid=$!
    done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment