2016-07-11 34 views
0

我正在設置一個安裝了nginx-lua的docker鏡像。該場景是在分段中進行基本身份驗證,但不是在生產中。我的想法是有一個ENV變量與舞臺名稱並檢查nginx.conf文件中的值。基於環境變量的NGINX基本認證

docker-compose.yml文件的內容(分期和生產階段ENV當然會prod):

docs-router: 
    build: ./nginx 
    environment: 
    - API_BASE_URI=staging.example.com 
    - DOCS_STATIC_URI=docs-staging.example.com 
    - STAGE=staging 
    ports: 
    - "8089:8089" 
    - "8090:8090" 

nginx.conf文件的內容:

... 

env API_BASE_URI; 
env DOCS_STATIC_URI; 
env STAGE; 

... 

http { 
    server { 
    listen 8089 default_server; 
    charset utf-8; 
    resolver 8.8.8.8; 
    access_log off; 

    proxy_set_header X-Real-IP $remote_addr; 
    proxy_set_header Host $host; 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

    location ~ ^(/.*\.(?:apib|svg))?$ { 
     set_by_lua_block $api_base_uri { return os.getenv("API_BASE_URI") } 
     set_by_lua_block $stage { return os.getenv("STAGE") } 
     set $unprotected "prod"; 

     if ($stage = $unprotected) { 
     auth_basic "Restricted Content"; 
     auth_basic_user_file /etc/nginx/.htpasswd; 
     } 

     proxy_pass https://$api_base_uri$1; 
     proxy_set_header Host $api_base_uri; 
    } 

    ... 

    } 

} 

但它的不工作。任何想法,我怎麼能做到這一點?

+0

那麼你的問題是什麼? –

+0

這種配置不起作用,我想知道我的配置是錯誤的,或者這個實現不會與NGINX一起工作。 –

+0

我的目標是擁有一個合適的NGINX配置的單個碼頭圖像,可以在任何階段部署,並只在特定環境中請求身份驗證。 –

回答

2

我只是在Serverfault的幫助下找到了解決方案。這是不是最好的,因爲URL是在nginx.conf文件,但它解決了我的問題:

我只是刪除了變量形成docker-compose.yml文件:

docs-router: 
    build: ./nginx 
    environment: 
    - API_BASE_URI=staging.example.com 
    - DOCS_STATIC_URI=docs-staging.example.com 
    ports: 
    - "8089:8089" 
    - "8090:8090" 

然後我映射的URL在nginx.conf文件:

... 

env API_BASE_URI; 
env DOCS_STATIC_URI; 

... 

http { 

    ## 
    # URL protection 
    ## 
    map $http_host $auth_type { 
    default "off"; 
    stage1.example.com "Restricted"; 
    stage2.example.com "Restricted"; 
    } 

    server { 
    listen 8089 default_server; 
    charset utf-8; 
    resolver 8.8.8.8; 
    access_log off; 

    proxy_set_header X-Real-IP $remote_addr; 
    proxy_set_header Host $http_host; 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

    location ~ ^(/.*\.(?:apib|svg))?$ { 
     set_by_lua_block $api_base_uri { return os.getenv("API_BASE_URI") } 

     auth_basic $auth_type; 
     auth_basic_user_file /etc/nginx/.htpasswd; 

     proxy_pass https://$api_base_uri$1; 
     proxy_set_header Host $api_base_uri; 
    } 

    ... 

    } 

} 

如果有更好的/更好的解決方案,請讓我知道。

+0

我剛剛遇到了一點更復雜的解決方案。我定義了一個像RESTRICTED_STAGES這樣的環境變量,幷包含需要保護的主機名(逗號分隔)。在Docker構建期間,我將解析這個變量,讀取主機名並用它們修改原始的'nginx.conf'文件 - 現在它是可配置的。 –

+0

我剛剛接受了我自己的解決方案,因爲沒有任何其他想法或建議。 –