【问题标题】:nginx (openresty) get current peernginx (openresty) 获取当前节点
【发布时间】:2020-04-08 07:55:00
【问题描述】:

在容器app的多个实例前面有一个openresty负载均衡器,负载均衡器会使用轮询将流量路由到每个app实例。 有没有办法可以将配对的后端服务器IP地址记录到redis中?上游是固定的,是动态的。

我尝试使用上游,但它似乎只适用于固定上游{},而不是动态的

docker-compose up --scale nginx_html_app=2
-- this is docker-compose.yml
nginx_html_app:
    build: nginx_html_app
proxy:
    build: proxy
    ports:
        - "9000:80"

-- this is proxy.conf
server{
    listen 80;
    set $upstream http://nginx_html_app
    location / {
        some_lua_block{
            # get paired backend IP, eg: 172.18.0.3 (nginx_html_app 1)
            # save to redis (know how to do this)
        }
        proxy_pass $upstream
    }
}

【问题讨论】:

    标签: nginx load-balancing openresty


    【解决方案1】:

    上游 IP 和端口在 ngx.var.upstream_addr 变量、header_filter_by_lualog_by_lua 中可用。但是首先登录会使请求等待您的写入完成,而在第二个中,网络套接字不可用,因此您需要将日志记录排队并在计时器中触发它。

    类似的东西(未经测试,但应该可以帮助你理解这个想法):

    app.lua - 单独的文件,我们需要它来缓存全局状态:

    M = {}
    
    local queue = {}
    
    function M.init()
      ngx.timer.every(1.0, function(premature)
        if premature then return end
        -- push queue to redis and clear it
      end)
    end
    
    function M.log()
      queue[#queue+1] = ngx.var.upstream_addr
    end
    
    return M
    

    nginx:

    init_worker_by_lua_block { require('app.lua').init() }
    
    
    log_by_lua_block { -- or header_filter_by_lua_block
      require('app.lua').log()
    }
    

    【讨论】:

    • ngx.var.upstream_addr 根据我的测试为空或为空。我在 access_lua_block 中尝试过。没试过 log_by_lua_block 的想法。不过不错!
    • 只有 nginx 与上游通信后才可用,看一下请求阶段顺序:github.com/openresty/lua-nginx-module#directives
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2011-10-24
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多