Skip to content
Justin SilverTECHNOLOGY, TRAVEL & EVERYTHING IN BETWEEN

Linux

NGINX Configuration Monitor

August 5, 2017

I wanted a way to quickly distribute configuration files to my servers and have NGINX automatically reload. I found a solution for Debian servers and adapted it for CentOS 7 here. You will first create a bash script, make it executable, then call it from a systemd service. The script uses inotifywait to monitor the /etc/nginx/sites-enabled directory for changes and reloads NGINX if the configuration is valid.

Bash Script


#!/bin/bash
# Check inotify-tools is installed or not
rpm -qa | grep -q inotify-tools &> /dev/null
if [ $? -ne 0 ]
then
  echo "Installing inotify-tools, please wait..."
  yum -y install inotify-tools
fi
while true
do
  inotifywait --exclude .swp -e create -e modify -e delete -e move /etc/nginx/sites-enabled
  # Check NGINX Configuration Test
  # Only Reload NGINX If NGINX Configuration Test Pass
  nginx -t
  if [ $? -eq 0 ]
  then
    echo "Reloading Nginx Configuration"
    service nginx reload
  fi
done

Make Executable


chmod +x /usr/local/bin/nginx-monitor

Systemd Service


[Unit]
Description=Nginx Config Monitor Service
After=nginx.service

[Service]
Type=simple
ExecStart=/usr/local/bin/nginx-monitor
Restart=on-abort

[Install]
WantedBy=multi-user.target

Start Service


chmod 755 /etc/systemd/system/nginx-monitor.service
# reload systemd services
systemctl daemon-reload
# start the service
service nginx-monitor start
# load after reboot
chkconfig nginx-monitor on
Adapted for CentOS from Auto Reload NGINX.