如何为多个环境创建单个 NGINX.conf 文件

Ana*_*ukh 2 nginx docker nginx-reverse-proxy nginx-config

我使用 NGINX 作为反向代理。

我有 3 个环境(开发、QA、生产)

考虑一下,develop的 IP 地址是 1.2.3.4,qa 是 4.3.2.1,production 是 3.4.1.2

我已经按如下方式配置了 nginx.conf 文件,并且在开发环境的情况下它可以正常工作。

在构建这些 docker-image 时,我已经明确提到应该构建图像的配置如下

cd conf/clustered-develop/;sudo docker build -t jcibts-swmdtr-dev.jci.com/nginx:1 --build-arg PORT=8765 --build-arg ENVIRONMENT=clustered-develop .
Run Code Online (Sandbox Code Playgroud)

要求是 docker-image 应该只构建 1,然后它将被推送到 Docker Trusted 存储库。

它将被提升到其他环境的 docker 可信存储库,而无需再次构建镜像。

我的问题是我能做些什么来为所有环境工作这些单一的 conf。

就像 ip 替换为 localhost 或 ip 替换为 127.0.0.1 (我都试过但没有工作)

worker_processes 4;

events { worker_connections 1024; }
http {

    sendfile on;

    upstream consumer-portal {

        server 1.2.3.4:9006;

    }

    upstream licenseportal {

        server 1.2.3.4:9006;

    }

server {
        listen 8765;

        location /consumer-portal/ {
            proxy_pass         http://consumer-portal/;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }

        location /licenseportal/ {
            proxy_pass         http://licenseportal/;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
 }


}
Run Code Online (Sandbox Code Playgroud)

moe*_*ius 7

根据这个优秀的答案

  1. 您可以使用模板配置(例如)构建一次映像/etc/nginx/conf.d/nginx.template,其中包含您希望在 dev、qa 和 prod 之间更改的所有值的变量名称。例如:

    upstream licenseportal {
      server ${NGINX_HOST}:${NGINX_PORT};
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 然后为所有环境运行相同的映像,envsubst在运行映像时使用,通过使用nginx.conf特定于环境的值替换模板中的变量来创建新映像:

    # For Develop
    docker run -d \
      -e NGINX_HOST='1.2.3.4' \
      -e NGINX_PORT='9006' \
      -p 9006:9006 \
      jcibts-swmdtr-dev.jci.com/nginx:1 \
      /bin/bash -c "envsubst < /etc/nginx/conf.d/nginx.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"
    
    # For Production
    docker run -d \
      -e NGINX_HOST='4.3.2.1' \
      -e NGINX_PORT='9006' \
      -p 9006:9006 \
      jcibts-swmdtr-dev.jci.com/nginx:1 \
      /bin/bash -c "envsubst < /etc/nginx/conf.d/nginx.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"
    
    Run Code Online (Sandbox Code Playgroud)

注意:要使其工作 -envsubst需要作为图像的一部分安装。IERUN apt-get -y update && apt-get -y install gettext