How to dynamically add an upstream in Nginx?

XadillaX picture XadillaX · Feb 22, 2017 · Viewed 10.8k times · Source

I mean add an upstream but not a server in an upstream.

That means I don't have an upstream block like:

upstream backend {
    # ...
}

I want create an upstream block dynamically. That is something like:

content_by_lua_block {
    upstream_block.add('backend');
    upstream_block.add_server('backend', '127.0.0.1', 8080);
    upstream_block.add_server('backend', '127.0.0.1', 8081);
    upstream_block.add_server('backend', '127.0.0.1', 8082);
    upstream_block.del_server('backend', '127.0.0.1', 8080);
}

proxy_pass http://backend

Answer

Alexander Altshuler picture Alexander Altshuler · Feb 23, 2017

You may use balancer_by_lua* and https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md

You will have a full control which upstream is selected for given request.

You may self provision you code or use existing upstream config as the source using https://github.com/openresty/lua-upstream-nginx-module