This is the hack approach to adding environment variables to the nginx configuration files. As with most Google results for this search, the reason is Docker.
I intended to deploy two Docker containers.
- An instance of an HTTP server providing a REST service (in my case, a JBoss application server running a Spring application)
- An nginx that provides a proxy to the REST service.
Why would I want to use a proxy? Load balancing, caching, firewalling... in my case, it was that the original application did not provide CORS and the nginx configuration does. You can see the nginx configuration in the proxy.conf file.
Both the port and the IP address of the JBoss instance are assigned by Docker dynamically. Docker provides a linking feature for service discovery that allows Docker containers to know the IP and port of services running on a specific container, but the quirk is that it relies on environment variables.
I'm not actually certain that adding environment variables to an nginx configuration file is impossible, but its at the very least very hard.
So this is what I did: I created the base configuration file, named it proxy.conf
and setup docker to add it to the conf.d
directory while building the image. The command is:
ADD proxy.conf /etc/nginx/conf.d/proxy.conf
In the proxy.conf
, I omitted the upstream
configuration, leaving that for later. I created another file, a run.sh
file and added it to the image using the Dockerfile. The file was as follows:
#!/bin/sh
(echo "upstream theservice { server $JBOSS_PORT_8080_TCP_ADDR:$JBOSS_PORT_8080_TCP_PORT; }" && cat /etc/nginx/conf.d/proxy.conf) > proxy.conf.new
mv proxy.conf.new /etc/nginx/conf.d/proxy.conf
service nginx start
What does is, it prepends the line with the upstream configuration.
Finally, I run the nginx from the run.sh
script. The Dockerfile command:
CMD bash run.sh
The trick is that since the container is initialized like that, the configuration file does not get permanently written and the configuration is updated accordingly.
Hi,
I've tried your solution. Although I do see the correct configuration at log output, when I pull the proxy.conf from the container I see the original proxy.conf. Do you know what might be going on?
Thanks!