Nginx environment variable substitution with Docker for SaaS apps
2 min readNov 16, 2021
Software as a service apps should store configuration values in environment variables when you rely on the twelve-factor app Saas guide. The twelve-factor rule says you should seperate config from your code, because configuration varies across environment stages: https://12factor.net/config
Since nginx version 1.19 it’s possible to replace values in nginx config files with given environment variables. This eases the build of self designed Dockerfiles for your nginx server dramatically. Let’s take a look at a simple example with docker compose:
version: '3.9'
services:
nginx:
image: nginx:1.19-alpine
ports:
- "8080:80"
environment:
FCGI_HOST: php
volumes:
- ./:/var/www/html:ro
- ./docker/vhost.template:/etc/nginx/templates/default.conf.template php:
image: webdevops/php:8.0-alpine
working_dir: /var/www/html
Our local vhost.template file looks like this:
server {
server_name server_name _;
listen 80 default_server;
root /var/www/html/web;
index index.php;
location / {
try_files $uri /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_pass ${FCGI_HOST}:9000;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include…