代码之家  ›  专栏  ›  技术社区  ›  Anand Deshmukh

如何创建单NGINX.conf公司多环境文件

  •  2
  • Anand Deshmukh  · 技术社区  · 6 年前

    我使用NGINX作为反向代理。

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

    开发是1.2.3.4,质量保证是4.3.2.1,生产是3.4.1.2

    我已经配置了nginx.conf公司文件如下所示,在下列情况下工作正常 发展 环境。

    在构建这些docker映像时,我已经明确地提到映像应该在哪个配置上构建,如下所示

    cd conf/clustered-develop/;sudo docker build -t jcibts-swmdtr-dev.jci.com/nginx:1 --build-arg PORT=8765 --build-arg ENVIRONMENT=clustered-develop .
    

    要求是docker映像应该只构建1个,然后将其推送到docker可信存储库。

    它将升级到其他环境的docker trusted repository,而无需重新构建映像。

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

    比如用localhost替换ip或者用127.0.0.1替换ip(我都试过了,但都没用)

    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;
            }
     }
    
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   moebius    6 年前

    根据这个极好的 answer :

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

      upstream licenseportal {
        server ${NGINX_HOST}:${NGINX_PORT};
      }
      
    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;'"
      

    注意 :以使其工作- envsubst公司 需要作为映像的一部分进行安装。即 RUN apt-get -y update && apt-get -y install gettext