Warning: Redis::connect(): connect() failed: Connection refused in /var/www/com.justinsilver/www/html/wp-content/plugins/nginx-helper/includes/redis-delete.php on line 15
Nginx Configuration Monitor - Justin Silver

Nginx Configuration Monitor

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.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *