【发布时间】:2019-04-02 12:53:13
【问题描述】:
我有这个 docker-compose 配置(它是我的 nginx 服务的一部分)
nginx-service:
image: nginx:latest
container_name: nginx-service
command: /bin/bash -c "exec nginx -g 'daemon off;'"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf
- ./nginx/sites-enabled:/etc/nginx/sites-enabled
restart: always
networks:
system-network:
aliases:
- nginx-service.docker
extra_hosts:
- serverIp:${CURRENT_SERVER_IP}
ports:
- 80:80
- 443:443
- 8081:8081
在此服务器中有一个 docker 容器,该容器不在 docker-compose 网络中,并在必要时自动创建。
我希望服务器的当前 ip 在 .env 文件中,为此我使用 extra_hosts 和这个 nginx 配置作为代理:
server {
listen 0.0.0.0:80;
server_name first.example.com;
location / {
proxy_pass http://serverIp:8082/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
这真的很管用!因为这个容器总是启动并且有 8082 端口。
但是这个配置不起作用,我无法修复它。你能告诉我如何解决这个问题吗?
server {
listen 0.0.0.0:80;
server_name second.example.com;
client_max_body_size 1024m;
location / {
set $status_proxy 0;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_http_version 1.1;
# proxy_set_header Connection "";
proxy_connect_timeout 960s;
proxy_send_timeout 960s;
proxy_read_timeout 960s;
send_timeout 960s;
if ($cookie_testingPort ~* "(60[\d]{3})") {
proxy_pass http://serverIp:$cookie_testingPort;
set $status_proxy 1;
}
if ($status_proxy = 0) {
return 400;
}
}
}
当我从 second.example.com 重定向时 - 尽管我在 cookie testingPort 中看到 docker 容器的正确端口和容器确实在服务器中具有 CURRENT_SERVER_IP,但 nginx 返回我“502 Bad Gateway”,该 CURRENT_SERVER_IP 在内部的主机文件中指定带有 NGINX 的容器
【问题讨论】:
-
if ($cookie_testingPort ~* "(60[\d]{3})")是什么意思或者你想用它达到什么目的?您是否使用端口连接到second.example.com? -
second.example.com - 此 URL 应将用户重定向到在从 6000 开始的特定端口范围上创建的容器,然后在这种情况下遵循 regExp。为了连接到它,我想使用 cookie 中的端口和在 hosts 文件中重新定义的地址。如果我正确指定了地址,而没有在主机中重新定义它,那么这个条件和重定向可以正常工作。但我想了解如何使其与主机文件中重新定义的 URL 一起工作
-
如果我理解正确,您的变量
$cookie_testingPort未定义。您在定义该变量的位置是否有额外的代码?此外,您正则表达式检查“60”+ 3 位数字,因此“6000”将不匹配。 -
对不起 60000 端口,我的意思是,$cookie_testingPort - 在提升时,nginx 确实是未定义的,但是当它被重定向到这个 URL 时,它是从用户那里读取的,然后在检查之后验证它应该被发送到容器,但此时它不能再读取记录在文件 hosts 中的信息
标签: docker nginx docker-compose