我想使用 nginx 創建一個簡單的反向代理來合并兩個開發應用程式。為此,我做了這個 nginx 配置:
upstream angulardev{
server ${DEV_HOST}:${ANGULAR_PORT};
}
upstream nestjsdev{
server ${DEV_HOST}:${NESTJS_PORT};
}
server {
listen 80;
listen [::]:80;
server_name localhost;
location / {
proxy_set_header Host $http_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-Proto $scheme;
proxy_pass http://angulardev;
}
location /api {
proxy_set_header Host $http_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-Proto $scheme;
proxy_pass http://nestjsdev;
}
}
所以你可以看到我使用了一些環境變數來創建這個組態檔。但是當我嘗試使用這個 docker compose 檔案來撰寫我的 docker 容器時:
version: '3.7'
services:
nginx:
image: nginx:1.19-alpine
volumes:
- "./conf/default.conf:/etc/nginx/conf.d/default.conf"
environment:
DEV_HOST: 192.168.1.10
ANGULAR_PORT: 4200
NESTJS_PORT: 8080
ports:
- 8000:80
我收到了這個錯誤:
nginx_1 | nginx: [emerg] invalid port in upstream "${DEV_HOST}:${ANGULAR_PORT}" in /etc/nginx/conf.d/default.conf:2
對我來說,這意味著 docker 在啟動之前沒有在 docker 內設定 env var。所以,我不知道我做錯了什么以及如何解決這個問題。
uj5u.com熱心網友回復:
您誤讀了錯誤訊息。它與是否設定環境變數無關。Nginx 根本不支持其組態檔中的環境變數。您看到該錯誤是因為 nginx 期待例如一個埠,但它卻找到了${ANGULAR_PORT},這在語法上是無效的。
如果你閱讀了Docker 鏡像的檔案,會有一個標題為“在 nginx 配置中使用環境變數”的部分。部分內容如下:
開箱即用的 nginx 不支持大多數配置塊中的環境變數。但是這個鏡像有個函式,會在nginx啟動前提取環境變數。
默認情況下,該函式讀取模板檔案
/etc/nginx/templates/*.template并將執行結果輸出envsubst到/etc/nginx/conf.d.
所以如果你想在你的 nginx 配置中使用環境變數,你需要這樣的東西:
version: '3.7'
services:
nginx:
image: nginx:1.19-alpine
volumes:
- "./conf/default.conf:/etc/nginx/templates/default.conf.template"
environment:
DEV_HOST: 192.168.1.10
ANGULAR_PORT: 4200
NESTJS_PORT: 8080
ports:
- 8000:80
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/505158.html
上一篇:如何在微服務之間轉發標頭?
