使用 NGINX Docker 镜像
Apply envsubst
在容器启动时的配置文件模板上。envsubst
包含在官方 NGINX docker 镜像中。
环境变量以表单引用$VARIABLE
or ${VARIABLE}
.
nginx.conf.模板:
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
server {
listen 80;
location / {
access_log off;
return 200 '${MESSAGE}';
add_header Content-Type text/plain;
}
}
}
Dockerfile:
FROM nginx:1.17.8-alpine
COPY ./nginx.conf.template /nginx.conf.template
CMD ["/bin/sh" , "-c" , "envsubst < /nginx.conf.template > /etc/nginx/nginx.conf && exec nginx -g 'daemon off;'"]
构建并运行 docker:
docker build -t foo .
docker run --rm -it --name foo -p 8080:80 -e MESSAGE="Hellou World" foo
NOTE:如果配置模板包含美元符号$
不应被替换,然后列出所有使用的变量作为参数envsubst
这样就只有那些被替换了。例如。:
CMD ["/bin/sh" , "-c" , "envsubst '$USER_NAME $PASSWORD $KEY' < /nginx.conf.template > /etc/nginx/nginx.conf && exec nginx -g 'daemon off;'"]
Nginx Docker 文档 https://hub.docker.com/_/nginx以供参考。寻找在 nginx 配置中使用环境变量.
在 nginx 配置中使用环境变量
开箱即用,nginx不支持内部环境变量
大多数配置块。但 envsubst 可以用作解决方法,如果
你需要在 nginx 之前动态生成 nginx 配置
开始。
这是使用 docker-compose.yml 的示例:
web:
image: nginx
volumes:
- ./mysite.template:/etc/nginx/conf.d/mysite.template
ports:
- "8080:80"
environment:
- NGINX_HOST=foobar.com
- NGINX_PORT=80
command: /bin/bash -c "envsubst < /etc/nginx/conf.d/mysite.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
The mysite.template
然后文件可能包含变量引用,例如
这:
listen ${NGINX_PORT}
;