brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: the nginx image fills in environment variables from /etc/nginx/templates

Nginx
~/tips/tip-nginx-docker-templates-envsubst

server {

Writes config from templates with your environment values when the official container starts.

nginx config files have no support for environment variables. The official Docker image adds it at startup, so one config can serve several setups.

server {
    listen 80;
    server_name ${SITE_NAME};
    location / {
        proxy_pass http://${BACKEND};
        proxy_set_header Host $host;
    }
}

Save that as default.conf.template, mount the folder at /etc/nginx/templates, and pass the values:

docker run -e SITE_NAME=example.com -e BACKEND=app:8080 \
  -v ./templates:/etc/nginx/templates:ro nginx:alpine

Before nginx starts, the entrypoint runs envsubst on every *.template file and writes the result to /etc/nginx/conf.d/ without the suffix. The output then has example.com and the backend filled in, while $host stays as it was.

That last part is the clever bit: the script only replaces variables that exist in the container’s environment, so nginx’s own variables survive. It also means a typo or a missing -e leaves ${SITE_NAME} in the file literally, and nginx then fails on it. A file with the same name in conf.d gets overwritten, so don’t mount your own default.conf at the same time. NGINX_ENVSUBST_FILTER limits which variables get replaced, which I’d set if your environment holds names that clash.

Further reading: nginx on Docker Hub (using environment variables)

Going deeper: ๐Ÿ›œ Guide: AdGuard Home + Tailscale (Secure Split-Horizon DNS)

More Nginx tips sudo certbot --nginx -d example.com -d www.example.com /data/nginx/custom/server_redirect.conf map $http_upgrade $connection_upgrade { proxy_intercept_errors on; proxy_redirect http://localhost:3000/ /app/; All Nginx tips (50) All topics

Link