'init_by_lua_block' 指令没有在 nginx 启动时执行

'init_by_lua_block' directive not getting executed on nginx start

我希望我的 lua 脚本之一在 nginx 服务器启动或重新加载时执行。我尝试使用 init_by_lua_block 和 init_by_lua_file 指令,但是当我 运行 nginx docker 时,我没有在 init_by_lua_block 中看到 lua 脚本的任何日志跟踪.我的 http 块如下所示。 nginx.config 位于容器 path/etc/nginx/nginx.conf .

http {
    sendfile on;
    init_by_lua_block /etc/nginx/lua/init.lua;
    include /etc/nginx/conf.d/proxy-config.conf;
 }

任何人都可以告诉我我在这里缺少什么吗?

init_by_lua_block

syntax: init_by_lua_block { lua-script }

https://github.com/openresty/lua-nginx-module#init_by_lua_block

init_by_lua_block 需要内联 Lua 代码,而不是 Lua 文件的路径。

使用dofile执行Lua脚本:

init_by_lua_block {
  dofile('/etc/nginx/lua/init.lua')
}

https://www.lua.org/manual/5.1/manual.html#pdf-dofile

或使用init_by_lua_file:

init_by_lua_file /etc/nginx/lua/init.lua;

更新:

您应该在 init_by_lua_* 指令中使用 NOTICE 日志记录级别(或更高级别),因为您的 error_log 配置尚未在此阶段应用:

Under the hood, the init_by_lua runs in the nginx configuration loading phase, so your error_log configuration in nginx.conf does not take effect until the whole configuration is loaded successfully (due to the bootstrapping requirements: the configuration loading MAY fail). And nginx initially uses a logger with the NOTICE filtering level upon startup which is effect in the whole first configuration loading process (but not subsequent configuration (re)loading triggered by the HUP signal).

https://github.com/openresty/lua-nginx-module/issues/467#issuecomment-82647228

因此,使用 ngx.log(ngx.NOTICE, ...)(或 ngx.WARNngx.ERR 等 — 参见 https://github.com/openresty/lua-nginx-module#nginx-log-level-constants)查看日志中的输出。

或者您可以使用 print。它相当于引擎盖下的 ngx.log(ngx.NOTICE, ...)https://github.com/openresty/lua-nginx-module#print