Sarga
Sarga

Reputation: 169

'init_by_lua_block' directive not getting executed on nginx start

I wanted one of my lua script to get executed whenever nginx server starts or is reloaded. I tried using init_by_lua_block and init_by_lua_file directive but i dont see any log traces for the lua script in init_by_lua_block when i run the nginx docker. My http block looks like below. nginx.config is located in container 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;
 }

Can anyone please tell me what I am missing here?

Upvotes: 0

Views: 3265

Answers (1)

Dmitry Meyer
Dmitry Meyer

Reputation: 1545

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 expects inlined Lua code, not a path to the Lua file.

Use dofile to execute Lua script:

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

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

or use init_by_lua_file:

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

UPD:

You should use the NOTICE logging level (or higher) in init_by_lua_* directives because your error_log configuration is not yet applied in this phase:

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

So, use ngx.log(ngx.NOTICE, ...) (or ngx.WARN, ngx.ERR, etc. — see https://github.com/openresty/lua-nginx-module#nginx-log-level-constants) to see the output in the log.

Alternatively you can use print. It's equivalent to ngx.log(ngx.NOTICE, ...) under the hood: https://github.com/openresty/lua-nginx-module#print

Upvotes: 1

Related Questions