shell – nginx: use environment variables

shell – nginx: use environment variables

With NGINX Docker image

Apply envsubst on template of the configuration file at container start. envsubst is included in official NGINX docker images.

Environment variable is referenced in a form $VARIABLE or ${VARIABLE}.


user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/;

events {
    worker_connections  1024;

http {
    server {
        listen       80;
        location / {
            access_log off;
            return 200 ${MESSAGE};
            add_header Content-Type text/plain;


FROM nginx:1.17.8-alpine
COPY ./nginx.conf.template /nginx.conf.template
CMD [/bin/sh , -c , envsubst < /nginx.conf.template > /etc/nginx/nginx.conf && exec nginx -g daemon off;]

Build and run docker:

docker build -t foo .
docker run --rm -it --name foo -p 8080:80 -e MESSAGE=Hellou World foo

NOTE:If config template contains dollar sign $ which should not be substituted then list all used variables as parameter of envsubst so that only those are replaced. E.g.:

CMD [/bin/sh , -c , envsubst $USER_NAME $PASSWORD $KEY < /nginx.conf.template > /etc/nginx/nginx.conf && exec nginx -g daemon off;]

Nginx Docker documentation for reference. Look for Using environment variables in nginx configuration.

Using environment variables in nginx configuration

Out-of-the-box, nginx doesn’t support environment variables inside
most configuration blocks. But envsubst may be used as a workaround if
you need to generate your nginx configuration dynamically before nginx

Here is an example using docker-compose.yml:

  image: nginx
    - ./mysite.template:/etc/nginx/conf.d/mysite.template
    - 8080:80
    - NGINX_PORT=80
  command: /bin/bash -c envsubst < /etc/nginx/conf.d/mysite.template > /etc/nginx/conf.d/default.conf && exec nginx -g daemon off;

The mysite.template file may then contain variable references like

listen ${NGINX_PORT};

You can access the variables via modules – I found options for doing it with Lua and Perl.

Wrote about it on my companys blog:

The TL;DR:

env API_KEY;

And then:

http {
  server {
    location / {
      # set var using Lua
      set_by_lua $api_key return os.getenv(API_KEY);

      # set var using perl
      perl_set $api_key sub { return $ENV{API_KEY}; };

EDIT: original blog is dead, changed link to wayback machine cache

shell – nginx: use environment variables

The correct usage would be $SOME_IP_from_env, but environment variables set from nginx.conf cannot be used in server, location or http blocks.

You can use environment variables if you use the openresty bundle, which includes Lua.

Leave a Reply

Your email address will not be published.