There are many ways to parse in variable into the nginx config file.
Some uses set_by_lua
which is offered by lua-nginx-module.
Some use envstubst
to populate varilabes into a template file.
Today I am going to show you how to do that with njs
the JS scripting engine for nginx.
## /etc/nginx/fetch_env.js
function fetch_upstream_host(r) {
return process.env.UPSTREAM_HOST;
}
function fetch_upstream_port(r) {
return process.env.UPSTREAM_PORT;
}
## /etc/nginx/nginx.conf
load_module modules/ngx_http_js_module.so;
env UPSTREAM_HOST;
env UPSTREAM_PORT;
http {
js_include fetch_env.js;
js_set $upstream_host fetch_upstream_host;
js_set $upstream_port fetch_upstream_port;
server {
# ....
location / {
# ....
proxy_pass http://$upstream_host:$upstream_port;
}
}
}