nginx auto-restart的有效方法

324 阅读1分钟

利用inotify对nginx的配置文件进行监听,从而实现配置文件有变化时可以自动重载nginx。

安装inotify

yum install inotify-tools

编写auto-restart.sh

#!/bin/sh 

# 初始配置文件的校验和
initial_checksum=$(find /opt/openresty/nginx/conf/ -type f -name '*.conf' -exec cksum {} \; | sort | cksum)

# 监视目录和文件变化
inotifywait -e modify,move,create,delete -mr --timefmt '%d/%m/%y %H:%M' --format '%T' \
  /opt/openresty/nginx/conf/ |
  while read date time; do
    new_checksum=$(find /opt/openresty/nginx/conf/ -type f -name '*.conf' -exec cksum {} \; | sort | cksum)

    if [[ "$new_checksum" != "$initial_checksum" ]]; then
      echo "At ${time} on ${date}, configuration file update detected."
      initial_checksum=$new_checksum
      nginx -s reload
    fi
  done