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:
Once you have the template configured, all you need to do is include it in the Docker compose file as:
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:
Will output the result as:
This allows Nginx to load the variable from envsubst.
For this quick guide, we utilized the envsubst utility to allow Nginx to read environment variables.