如何在 Docker 容器里的 nginx 配置中使用环境变量?

查看Nginx的官方镜像,可以找到下面这段话

Using environment variables in nginx configuration

Out-of-the-box, nginx doesn't support environment variables inside most configuration blocks. But envsubst may be used as a workaround if you need to generate your nginx configuration dynamically before nginx starts.

Here is an example using 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 && nginx -g 'daemon off;'"

The mysite.template file may then contain variable references like this:

listen ${NGINX_PORT};

Nginx官方提供了一种用 docker compose启动的方法,启动时传入两个环境变量到容器中,并挂载了一个 mysite.template 的文件。

比如在 default.confproxy_pass http://本机ip:端口,那么在 mysite.template 中则相应地表示为 proxy_pass http://${NGINX_HOST}:${NGINX_PORT},通过 envsubst 命令以及输入输出重定向,nginx容器启动之后,default.cof 中的两个值就会被容器中的环境变量替换。

实际上,命令 envsubst < /etc/nginx/conf.d/mysite.template > /etc/nginx/conf.d/default.conf 执行时,会将 mysite.template 文件中所有带 $ 符的字符视为变量读取出来,然后找相应的环境变量做替换,最后将结果输出到 default.conf 中,可是 Nginx 本身有许多的自定义变量如$host $remote_addr等,这些都会被 envsubst命令替换,如果环境变量中并没有这些值,则会造成这些都被替换成空值,最终导致 nginx.conf 不合法而无法启动。

所以,需要指定只替换我们需要的那两个变量,将上面的命令按照如下修改即可

envsubst '$NGINX_HOST $NGINX_PORT $HOST_IP' < /etc/nginx/mysite.template > /etc/nginx/conf.d/default.conf

如果是自己制作的镜像,只需要修改 nginx 的 Dockfile ,增加如下内容:

COPY mysite.template /etc/nginx

CMD envsubst '$NGINX_HOST $NGINX_PORT $HOST_IP' < /etc/nginx/mysite.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'

相应的docker run命令:

docker run --name nginx -p 80:80 --env NGINX_HOST=localhost --env NGINX_PORT=80 --env HOST_IP=$(ifconfig eth0|grep inet|awk '{print $2}') --restart always -d nginx:tag

基本上任何文件需要读取环境变量的都可以采用这种方法。

如需转载,请注明出处: https://www.chadou.me/p/221

最新发布