The following is based on the Openresty balancer_by_lua configuration directive, which uses Ngx.crc32_long to generate a hash from the source address and destination port to achieve a simple ip_hash upstream. For reference only
Upstream backend{
server 0.0.0.0;
Balancer_by_lua_block {
Local balancer = require "Ngx.balancer"
Local host = {"192.168.1.111", "192.168.1.112"}
Local backend = ""
Local port = ngx.var.server_port
Local remote_ip = ngx.var.remote_addr
local key = REM Ote_ip. Port
Local hash = Ngx.crc32_long (key);
hash = (hash% 2) + 1
backend = Host[hash]
ngx.log (NGX. DEBUG, "ip_hash=", Ngx.var.remote_addr, "hash=", Hash, "up=", Backend, ":", port)
local OK, err = Balancer.set_curr Ent_peer (backend, port)
if not OK then
Ngx.log (NGX. Err, "Failed to set the current peer:", err)
return Ngx.exit ($)
end
Ngx.log (NGX. DEBUG, "current peer", backend, ":", Port)
}
}
server {
listen;
Listen 8080;
Listen 7777;
server_name *.x.com location
/{
proxy_pass http://backend;
}
}
Reference:
Https://github.com/openresty/lua-nginx-module