Nginx

Can Nginx Use Environment Variables?

Nginx is a powerful web server and reverse proxy that has become a default choice for most developers. With the rise of cloud computing and containers such as Docker, deploying multiple applications using Nginx is easy and efficient.

However, when you run applications on cloud hosting platforms such as AWS, GCP, Azure, etc., or an Nginx server, you need to set the port to listen on. This can be a problem as the port to listen on is defined in an environment variable.

Nginx does not support environment variables in its configuration. However, that does not mean that there is no solution to use environment variables in Nginx.

In this quick guide, we will discuss how to use envsubst in Nginx to use environment variables.

What is envsubst?

Envsubst is a command-line utility that allows you to substitute the values of environment variables. It is part of the gettext utilities, which means it is available in all official nginx docker images, which means applying the solution is very easy. All we need to do is apply envsbst on the template of the configuration file of the docker container

For example, include a template /etc/nginx/templates/nginx.conf.template and add the following entry:

listen ${NGINX_PORT};

Once you have the template configured, all you need to do is include it in the Docker compose file as:

image: nginx
volumes:
   - ./templates:/etc/nginx/templates
  ports:
   - "80"
  environment:
   - NGINX_HOST=localhost
   - NGINX_PORT=8080

Once you run the container, it read the template files specified in the volume entry /etc/nginx/templates/*.templates and calls the envsubstr, which reads the environment variables stored. It then stores the value in /etc/nginx/conf.d

Therefore, the entry such as:

listen ${NGINX_PORT};

Will output the result as:

listen       8080;

This allows Nginx to load the variable from envsubst.

Conclusion

For this quick guide, we utilized the envsubst utility to allow Nginx to read environment variables.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list