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
.
inotify-tools
-> https://github.com/inotify-tools/inotify-tools
#!/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