Kevin Burke
Kevin Burke

Reputation: 64964

Dynamically listen on an nginx port

I'd like to pass a port to Nginx to listen on dynamically. So I can write something like:

PORT=4567 nginx -c $PWD/nginx.conf

and then have an nginx config that looks something like:

http {
    server {
        listen $PORT;
    }
}

and have nginx listen on the specified port. I tried compiling nginx with lua support, and writing:

events {
    worker_connections 200;
}

env SERVER_PORT;

http {
    server {
        set_by_lua_block $sp {
            return os.getenv("SERVER_PORT");
        }
        listen $sp;
        root /Users/kevin/code/nginx-testing;
    }
}

But this doesn't work, either; $sp doesn't get defined until the rewrite phase.

Are there any options here or am I resigned to rewriting the config file via sed or similar before starting nginx?

Kevin

Upvotes: 2

Views: 3824

Answers (1)

xiaochen
xiaochen

Reputation: 1305

The listen directive does not support nginx variable or ENV variable. So it cannot listen on a nginx port dynamically.

Dynamical listen via ENV variable is technically feasible, you should modify nginx core.
But it cannot be implemented via nginx variable, nginx must listen on some specified port before receiving http requests. (nginx variable system works on http request.)


You can write some script to modify "listen" directive before starting nginx, which is a not-so-good way to implement dynamic listen.

Upvotes: 6

Related Questions