[从https://stackoverflow.com/questions/21933955交叉发布和编辑,因为对于StackOverflow来说,它过于像sysadmin。]
我有一个运行Nginx的Docker容器,该容器链接到另一个Docker容器。第二个容器的主机名和IP地址在启动时作为环境变量加载到Nginx容器中,但是在此之前是未知的(它是动态的)。我希望我nginx.conf
使用这些值-例如
upstream gunicorn {
server $APP_HOST_NAME:$APP_HOST_PORT;
}
如何在启动时将环境变量放入Nginx配置中?
编辑1
在下面建议的答案之后,这是整个文件:
env APP_WEB_1_PORT_5000_TCP_ADDR;
# Nginx host configuration for django_app
# Django app is served by Gunicorn, running under port 5000 (via Foreman)
upstream gunicorn {
server $ENV{"APP_WEB_1_PORT_5000_TCP_ADDR"}:5000;
}
server {
listen 80;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location /static/ {
alias /app/static/;
}
location /media/ {
alias /app/media/;
}
location / {
proxy_pass http://gunicorn;
}
}
重新加载nginx然后出现错误:
$ nginx -s reload
nginx: [emerg] unknown directive "env" in /etc/nginx/sites-enabled/default:1
编辑2:更多详细信息
当前环境变量
root@87ede56e0b11:/# env | grep APP_WEB_1
APP_WEB_1_NAME=/furious_turing/app_web_1
APP_WEB_1_PORT=tcp://172.17.0.63:5000
APP_WEB_1_PORT_5000_TCP=tcp://172.17.0.63:5000
APP_WEB_1_PORT_5000_TCP_PROTO=tcp
APP_WEB_1_PORT_5000_TCP_PORT=5000
APP_WEB_1_PORT_5000_TCP_ADDR=172.17.0.63
根目录nginx.conf:
root@87ede56e0b11:/# head /etc/nginx/nginx.conf
user www-data;
worker_processes 4;
pid /var/run/nginx.pid;
env APP_WEB_1_PORT_5000_TCP_ADDR;
站点nginx配置:
root@87ede56e0b11:/# head /etc/nginx/sites-available/default
# Django app is served by Gunicorn, running under port 5000 (via Foreman)
upstream gunicorn {
server $ENV{"APP_WEB_1_PORT_5000_TCP_ADDR"}:5000;
}
server {
listen 80;
重新加载nginx配置:
root@87ede56e0b11:/# nginx -s reload
nginx: [emerg] directive "server" is not terminated by ";" in /etc/nginx/sites-enabled/default:3
app_web_1
,它将获得一个新的IP地址,因此您也需要重新启动nginx容器。Docker将通过更新将其重新启动,/etc/hosts
因此您无需更改nginx配置文件。
server $ENV{"APP_WEB_1_PORT_5000_TCP_ADDR"}:5000;
为server app_web_1:5000;