使用具有多个端口的 nginx 上游组

jay*_*yme 11 nginx

我想对多个端口使用相同的上游定义:

upstream production {
    server 10.240.0.26;
    server 10.240.0.27;
}
server {
    listen 80;
    server_name some.host;
    location / {
        proxy_pass http://production:1234;
    }
}
server {
    listen 80;
    server_name other.host;
    location / {
        proxy_pass http://production:4321;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用该配置nginx -tthrows:upstream "production" may not have port 1234并返回退出代码 1。

当我尝试将proxy_passURL(或部分)定义为如下变量时:

set $upstream_url "http://production:1234"
set $upstream_host production;
set $upstream_port 1234;
proxy_pass $upstream_url;
# or
proxy_pass http://production:$upstream_port;
# or
proxy_pass http://$upstream:$upstream_port;
Run Code Online (Sandbox Code Playgroud)

Nginx 尝试通过解析器解析我的上游名称:

 *16 no resolver defined to resolve production, client: ...., server: some.host, request: "GET / HTTP/1.1", host: "some.host"
Run Code Online (Sandbox Code Playgroud)

对我来说,proxy_pass 文档听起来好像完全不应该发生;

服务器名称、端口和传递的 URI 也可以使用变量指定:

proxy_pass http://$host$uri; 甚至像这样:

proxy_pass $request; 在这种情况下,在描述的服务器组中搜索服务器名称,如果没有找到,则使用解析器确定。

使用 nginx 版本测试:

  • 1.6
  • 1.9
  • 1.10
  • 1.11

我错过了什么吗?有没有办法解决这个问题?

Ale*_*Ten 17

您必须serverupstream. 如果您不这样做,nginx 会将其设置为80. 所以server 10.240.0.26;实际上意味着server 10.240.0.26:80;.

你可以定义几个上游块:

upstream production_1234 {
    server 10.240.0.26:1234;
    server 10.240.0.27:1234;
}
upstream production_4321 {
    server 10.240.0.26:4321;
    server 10.240.0.27:4321;
}
server {
    listen 80;
    server_name some.host;
    location / {
        proxy_pass http://production_1234;
    }
}
server {
    listen 80;
    server_name other.host;
    location / {
        proxy_pass http://production_4321;
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是配置您的本地 DNS 以将主机名解析production为多个 IP,在这种情况下,nginx 将全部使用它们。

http://nginx.org/r/proxy_pass:如果域名解析为多个地址,则所有地址都将以循环方式使用。

server {
    listen 80;
    server_name some.host;
    location / {
        proxy_pass http://production:1234;
    }
}
Run Code Online (Sandbox Code Playgroud)


Ter*_*nen 5

当您使用上游时,端口在上游块中定义:

upstream production {
    server 10.240.0.26:8080;
    server 10.240.0.27:8081;
}
Run Code Online (Sandbox Code Playgroud)

换句话说,nginx 将proxy_pass参数解析为上游组或一host:port对。当您使用变量作为参数时,它仅解析为host:port配对。