This project shows HOWTO
create a Docker container using nginx where the nginx server can dynamically
acquire values from environment variables passed in by docker (e.g. using the -e
command).
Build it.
./build.sh
Run it.
docker run -p 81:81 -e PORT=81 --rm nginx-port:local
docker run -p 82:82 -e PORT=82 --rm nginx-port:local
docker run -p 83:83 -e PORT=83 --rm nginx-port:local
Observe it.
Note the following.
- The Angular application is a vanilla one using the ng-cli command
ng new
. This application is necessary to show only a toy deployment of a client-side application with nginx as the HTTP server. - In the
Dockerfile
, we haveCMD ["nginx", "-g", "daemon off;"]
to force nginx to run in the foreground. The-g
is aglobal
setting. This option of turning off daemon mode is useful for debugging and should be turned off for production. - Note that we are using
envsubst
to acquire the values of the environment variables. This approach is the recommended way. Look at thedocker-entrypoint.sh
script. We are using a nginx configuration templatenginx-default.conf.template
to help. - Elsewhere, people suggest using openresty. This approach took me down a rabbit hole. Supposedly, openresty can use
lua
andperl
inside thenginx.conf
file to acquire environment variables. If you figure outHOTWO
do this approach successfully, email me. ;) - This approach might help with Azure's Linux App Service VNET Integration where they pass in
-e PORT=<some_port>
(<some_port>
is a random value) to the container. The example they show is with a Node.js Express app which has theprocess.env.PORT
API access to environment variables (server-side applications like flask are also able to acquire environment variable values too e.g.os.getenv('PORT', 80)
). However, with a client-side application like Angular hosted onnginx
, this approach will help (as Angular will not have those API hooks).
Check out Charles Petzold. He's my favorite author when it comes to programming books.
@misc{oneoffcoder_nginx_port_2019,
title={Docker container show how to dynamically set ports from environment variable},
url={https://github.com/oneoffcoder/docker-containers/tree/master/nginx-port},
journal={GitHub},
author={One-Off Coder},
year={2019},
month={Jul}}