Docker cookbook · Beginner
Configure nginx from environment variables
Use one nginx image across environments with different upstream URLs and server names.
Approach
The official nginx image renders files in /etc/nginx/templates/*.template with envsubst at startup,
writing them to /etc/nginx/conf.d/. Put ${VAR} placeholders in the template and pass variables at run time.
Solution
# default.conf.template
server {
listen 8080;
server_name ${SERVER_NAME};
location /api/ { proxy_pass ${API_UPSTREAM}; }
location / { root /usr/share/nginx/html; try_files $uri /index.html; }
}
FROM nginx:1.29-alpine
COPY default.conf.template /etc/nginx/templates/
COPY dist/ /usr/share/nginx/html/
Pitfalls
- nginx's own variables like
$uriare left alone only because they aren't set in the environment; to be safe setNGINX_ENVSUBST_FILTERto substitute only your prefix. - Forgetting the
.templatesuffix, so the file is copied without substitution.
Variations
- The
nginxinc/nginx-unprivilegedimage to run as non-root on port 8080. - Mount the template as a ConfigMap in Kubernetes.
Further reading: Official nginx image
Reference: https://hub.docker.com/_/nginx
More Docker recipes
- Add a healthcheck to an HTTP service
- Build a layered image for a Spring Boot app
- Build a production image for a Node.js service
- Build a production image for a Python web app
- Build, cache and push images in GitHub Actions
- Build one image tag for amd64 and arm64
- Develop with Compose and live reload
- Make containers cope with dependencies that start slowly