【问题标题】:How do you properly watch and reload Nginx conf?您如何正确观看和重新加载 Nginx conf?
【发布时间】:2013-05-29 14:47:52
【问题描述】:

我有两个问题:

  • nginx -s reloadpkill -HUP -F nginx.pid之间有区别吗
  • 查看 Nginx conf 文件并在更改后测试 conf 文件 (nginx -t) 的最简单方法是什么,如果它通过重新加载 Nginx。这可以通过runit 或像 Supervisor 这样的流程管理器来完成吗?

【问题讨论】:

  • -F 还是-f(我的pkill 上没有-F
  • 至少在 Ubuntu 13.04 下是 -F--pidfile

标签: nginx


【解决方案1】:
#!/bin/bash

# NGINX WATCH DAEMON
#
# Author: Devonte
#
# Place file in root of nginx folder: /etc/nginx
# This will test your nginx config on any change and
# if there are no problems it will reload your configuration
# USAGE: sh nginx-watch.sh

# Set NGINX directory
# tar command already has the leading /
dir='etc/nginx'

# Get initial checksum values
checksum_initial=$(tar --strip-components=2 -C / -cf - $dir | md5sum | awk '{print $1}')
checksum_now=$checksum_initial

# Start nginx
nginx

# Daemon that checks the md5 sum of the directory
# ff the sums are different ( a file changed / added / deleted)
# the nginx configuration is tested and reloaded on success
while true
do
    checksum_now=$(tar --strip-components=2 -C / -cf - $dir | md5sum | awk '{print $1}')

    if [ $checksum_initial != $checksum_now ]; then
        echo '[ NGINX ] A configuration file changed. Reloading...'
        nginx -t && nginx -s reload;
    fi

    checksum_initial=$checksum_now

    sleep 2
done

【讨论】:

    【解决方案2】:

    至少在 Unix 上,“重新加载”操作和 HUP 信号都被视为一个,这要归功于声明代码

    ngx_signal_t  signals[] = {
        { ngx_signal_value(NGX_RECONFIGURE_SIGNAL),
          "SIG" ngx_value(NGX_RECONFIGURE_SIGNAL),
          "reload",
          ngx_signal_handler },
    

    src/os/unix/ngx_process.c。在ngx_signal_handler()相同的常用代码

        case ngx_signal_value(NGX_RECONFIGURE_SIGNAL):
            ngx_reconfigure = 1;
            action = ", reconfiguring";
            break;
    

    被执行,为共同的重新配置做准备。

    要在修改文件时触发操作,您可以创建 crontab 并确定检查周期,或使用 inotifywait

    要确定 nginx -t 是否有错误,请检查 bash 文件中的返回码 $?

    nginx -t
    if [ $? -eq 0 ] then;
        nginx -s reload
    fi
    

    注意:你也可以使用service nginx reload

    (查看返回码检查示例here

    【讨论】:

    • 其实我平时用service nginx reload
    • 有一个错字,应该是nginx -t而不是最后一个代码块中的linux -t。 (由于愚蠢的“编辑需要六个字符”规则而无法更改)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 2014-01-31
    • 1970-01-01
    • 2015-06-02
    • 2018-05-05
    • 1970-01-01
    相关资源
    最近更新 更多