问题原文
原帖链接 · Hugo Rodger-Brown · CC BY-SA 4.0
I have a docker container running Nginx, that links to another docker container. The host name and IP address of the second container is loaded into the Nginx container as environment variables on startup, but is not know before then (it's dynamic). I want my nginx.conf to use these values - e.g.
upstream gunicorn {
server $APP_HOST_NAME:$APP_HOST_PORT;
}
How can I get environment variables into the Nginx configuration on startup?
EDIT 1
This is the entire file, after the suggested answer below:
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;
}
}
Reloading nginx then errors:
$ nginx -s reload
nginx: [emerg] unknown directive "env" in /etc/nginx/sites-enabled/default:1
EDIT 2: more details
Current environment variables
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
Root 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;
Site nginx configuration:
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;
Reload nginx configuration:
root@87ede56e0b11:/# nginx -s reload
nginx: [emerg] directive "server" is not terminated by ";" in /etc/nginx/sites-enabled/default:3
已采纳解答
原帖链接 · David · CC BY-SA 4.0
Here another one with envsubst.
nginx docker image already runs envsubst through /docker-entrypoint.d/20-envsubst-on-templates.sh. You only need to place a template file in the right place: /etc/nginx/templates/my-file.conf.template.
Then, you can create a dedicated template file only for variables with one or more map clauses that we will use as our custom variables. You must choose a name for the conf.d file so that it is the first one that nginx takes.
This is the basic concept explained with docker-compose and three files:
docker-compose.yml:
version: "3.9"
services:
nginx:
image: nginx:1.23
volumes:
- ./template-variables:/etc/nginx/templates/10-variables.conf.template:ro
environment:
EXTERNAL_IP: "1.2.3.4"
template-variables:
map $host $external_ip {
default "$EXTERNAL_IP";
}
nginx.conf:
server {
location / {
proxy_set_header X-Real-IP $external_ip;
}
}
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
