Is there a way to specify port range in nginx config upstream block?

Viewed 2059

I'm looking for a way to specify a port range in the nginx upstream block.

Is there a way to turn this:

upstream backend {

    least_conn;

    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
    server 127.0.0.1:3002;
    server 127.0.0.1:3003;
    server 127.0.0.1:3004;
    server 127.0.0.1:3005;
}

into something like this?:

upstream backend {

    least_conn;

    server 127.0.0.1:[3000:3005]
}
1 Answers

One way to approach to operate host with Openresty which is based on Nginx and is capable of running Lua plugins. The snippet of code to make it work would look like this

upstream backend {
        balancer_by_lua_block {
        local balancer = require "ngx.balancer"
        local start_port=3000
        local max_port=start_port+5
        repeat
            local ok, err = balancer.set_current_peer('127.0.0.1', start_port)
            if not ok then
                ngx.log(ngx.ERR, "failed to set the current peer: ", err)
                return ngx.exit(500)
        end
        start_port=start_port+1
        until start_port>max_port
    } 
Related