Reputation: 24077
I use a simple Nginx docker container to serve some static files. I deploy this container to different environments (e.g. staging, production etc) using Kubernetes which sets an environment variable on the container (let's say FOO_COUNT
).
What's the easiest way of getting Nginx to pass the value of FOO_COUNT
as a header on every response without having to build a different container for each environment?
Upvotes: 2
Views: 6338
Reputation: 11280
This was made possible in nginx 1.19+. This functionality is now builtin.
All you need to do is add your default.conf.template
file (it looks for *.template suffix) to /etc/nginx/templates
and the startup script will run envsubst
on it, and output to /etc/nginx/conf.d
.
Read more at the docs, see an example here https://devopsian.net/notes/docker-nginx-template-env-vars/
Upvotes: 1
Reputation: 16294
Out-of-the-box, nginx doesn't support environment variables inside most configuration blocks. But, you can use envsubst
as explained in the official nginx Docker image.
Just create a configuration template that's available inside your nginx container named, e.g. /etc/nginx/conf.d/mysite.template
.
It contains your nginx configuration, e.g.:
location / {
add_header X-Foo-Header "${FOO_COUNT}";
}
Then override the Dockerfile command with
/bin/bash -c "envsubst < /etc/nginx/conf.d/mysite.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"
If you're using a docker-compose.yml
file, use command.
Kubernetes provides a similar way to override the default command in the image.
Upvotes: 2