I want to create a simple reverse proxy using nginx to merge two dev apps. To do that, I have made this nginx configuration :
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;
}
}
So has you can see I have used some env var to create this config file. But when I try to compose my docker container using this docker compose file :
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
I got this errors :
nginx_1 | nginx: [emerg] invalid port in upstream "${DEV_HOST}:${ANGULAR_PORT}" in /etc/nginx/conf.d/default.conf:2
For me, that mean docker as not set env var inside the docker before launch it. So, I don't know what I'm doing wrong and how to solve that.
CodePudding user response:
You are misreading the error message. It has nothing to do with whether the environment variables are set or not. Nginx simply does not support environment variables in its configuration files like that. You're seeing the error because nginx is expecting e.g. a port, and instead it finds ${ANGULAR_PORT}
, which is syntactically invalid.
If you read the documentation for the Docker image, there is a section titled "Using environment variables in nginx configuration". That reads, in part:
Out-of-the-box, nginx doesn't support environment variables inside most configuration blocks. But this image has a function, which will extract environment variables before nginx starts.
By default, this function reads template files in
/etc/nginx/templates/*.template
and outputs the result of executingenvsubst
to/etc/nginx/conf.d
.
So if you want to use environment variables in your nginx configuration, you need something like this instead:
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