Docker cookbook · Beginner

Configure nginx from environment variables

Use one nginx image across environments with different upstream URLs and server names.

Create a free account to save this page, take notes and track your progress. Sign in

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 $uri are left alone only because they aren't set in the environment; to be safe set NGINX_ENVSUBST_FILTER to substitute only your prefix.
  • Forgetting the .template suffix, so the file is copied without substitution.

Variations

  • The nginxinc/nginx-unprivileged image 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

Was this page helpful?