Docker nginx configuration template example with env vars
Until nginx v1.19, you had to either bake in the image a ready configuration file or mount it at runtime.
Often, you would need to template the nginx config file. This was made possible since v1.19 in a convenient way using environment variables.
First, you need a template to copy. Create default.conf.template file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
server { listen 80; server_name ${NGINX_PORT}; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; root /usr/share/nginx/html; index index.html index.htm;}}
In the Dockerfile, we need to place the *.template file in a specific location, /etc/nginx/templates.
On startup, the nginx entrypoint script scans this directory for files with *.template suffix by default, and it runs envsubst.
The envsubst parse the template using the shell interpolation and replaces shell variables with values from environment variables.
It outputs to a file in /etc/nginx/conf.d/.
If you’re using $var, and there’s no such env-var, it will stay as is in the output file.
In the above file, $host and $remote_addr are such examples. We want them to stay as parameters in the output file, as they are parameters used by nginx.