openresty에서 lua를 이용한 health check url을 만들었다. 


nginx는 파일 기반으로 되어 있고 문법이 그다지 친절하지 않아서, openresty의 lua를 이용하면 좀 shared memory를 공유하는 기법이 있다. 전역 변수를 lua_shared_dict을 사용하면 모든 worker에서 서로 공유할 수 있어 편리한다.


공유 dict에 값이 없으면 200으로 처리해 서비스되도록 한다. 그리고 공유 메모리(lua_shared_dict)의 크기는 작게 한다. 



http {

    lua_shared_dict dicts    16k;

    

    ....

     server {

        server_name _;


        listen 80;

        root /...


        location / {

            return 404;

        }


        location ~* \.(?:ico|css|js|gif|jpe?g|png|gif|eot|ttf|ott|woff2?|swf|svg|zip)$ {

            expires 1y;

        }


        location /health_off {

            default_type text/html;

            content_by_lua_block {

                local d = ngx.shared.dicts

                d:set("health", 400)

                ngx.say("health-off")

             }

             allow       192.168.0.0/16;

             allow       172.16.0.0/12;

             allow       127.0.0.1;

             deny        all;

         }


        location /health_on {

            default_type text/html;

            content_by_lua_block {

                local d = ngx.shared.dicts

                d:set("health", 200)

                ngx.say("health-on")

            }

            allow       192.168.0.0/16;

            allow       172.16.0.0/12;

            allow       127.0.0.1;

            deny        all;

        }


        location /health_check.html {

            access_log  off;

            allow       all;


            default_type text/html;

            access_by_lua_block {

                local dogs = ngx.shared.dicts

                local status = tonumber(dogs:get("health")) or 200

                if status == 400 then

                        return ngx.exit(400)

                end

                return ngx.exit(200)

            }

        }

...

}




결과는 다음과 같다. 


$ curl -i http://localhost/health_check.html

200

$ curl -i http://localhost/health_off

$ curl -i http://localhost/health_check.html

400

$ curl -i http://localhost/health_on

$ curl -i http://localhost/health_check.html

200



**************


진짜 주의할 점은 ngx.exit 사용시 ngx.say를 함께 사용해서는 안된다. ngx.exit 앞에 ngx.say를 사용하면 exit 값이 나타나지 않고 200으로만 리턴한다. ngx.exit를 사용할 때는 ngx.say를 사용하지 않는다. 



Posted by 김용환 '김용환'

댓글을 달아 주세요