0. Benefits of dynamic Upstream
Openresty author, recently also open source (not open source when I write this article) they have used the Balancer-by-lua feature, progress issues. Can dynamically modify the upstream, using reverse proxy proxy_pass, to the back-end process or machine: dynamic load balancing control; smooth up and down service, upgrade service; High possible guarantee – Auto kick offline service downline; 1. First, the principle
Ideas for reference from
2 directly on the configuration code
http{lua_shared_dict _g 1m;
# NGX Multi-process global shared memory, saving upstream value ... upstream default_upstream {server unix:/var/run/app-1.sock;
Server 127.0.0.0.:38888;
KeepAlive 24; } ... server{location =/_switch_upstream {Content_by_lua ' local ups = Ngx.req.get_uri _args () ["upstream"] if ups = Nil then Ngx.say ("Usage:curl/_switch_upstream?upstream=u Nix:/path-to-sock-file ") return end Local host = Ngx.var.http_host Loca L UPS_SRC = ngx.shared._g:get (host) Ngx.log (NGX. WARN, host, "Change upstream from", Ups_src, "to", UPS) Ngx.shared._g:set (host, UPS) Ngx.say (
Host, "Change upstream from", Ups_src, "to", UPS) '; } location ~ (^/api/|^/p/|^/m/|^/oauthapi/) {Set_by_lua $my _upstream ' local ups = Ngx.shared._g : Get (Ngx.var.http_host) if UPS ~= Nil then ngX.log (NGX. ERR, "get [", UPS, "] from ngx.shared") Return UPS end return "Default_upstream" '
;
Proxy_next_upstream off;
Proxy_set_header X-real-ip $remote _addr;
Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;
Proxy_set_header Host $host;
Proxy_http_version 1.1;
Proxy_set_header Connection "";
Proxy_pass http://$my _upstream; }
}
}
3. Usage
When you need to switch back-end upstream, use the command:
Curl Http://127.0.0.1/_switch_upstream?upstream=unix:/path-to-sock-file
Can be changed directly to the local socket file, or it can be ip:port, but the configuration is preset to a upstream name.