如何用nginx在一个端口上代理多个tcpstream

使用nginx http指令,可以在同一个端口上使用不同名称的多个服务器:

server { listen 80; server_name server1.example.com; location / { proxy_pass http://server1.example.com; } } server { listen 80; server_name server2.example.com; location / { proxy_pass http://server2.example.com; } } 

有可能让nginx代理多个mysql服务器在同一个端口上有不同的名字,就像你可以使用http? 他们不是集群或任何东西的一部分。 有不同的,无关的表。

 stream { upstream db1.example.com { server db1.example.com:3306; #server_name db1.example.com; "server_name" directive is not allowed here } upstream db2.example.com { server db2.example.com:3306; } server { listen 3306; proxy_pass db1.example.com; } #duplicate "3306" address and port pair #server { listen 3306; proxy_pass db2.example.com; } } 

是的,如果nginx是用--with-stream编译的。 https://www.nginx.com/resources/admin-guide/tcp-load-balancing/


以下是使用相同端口的示例之一:

 upstream stream_backend { hash $remote_addr; server backend1.example.com:12345; server backend2.example.com:12345; server backend3.example.com:12346; } 

第二次更新:

你显然不能做这样的事情:

 stream { upstream db1.example.com { server db1.example.com:3306; #server_name db1.example.com; "server_name" directive is not allowed here } upstream db2.example.com { server db2.example.com:3306; } server { listen 3306; proxy_pass db1.example.com; } #duplicate "3306" address and port pair #server { listen 3306; proxy_pass db2.example.com; } } 

因为上游db1.example.com的nginx代理正在与db2.example.com竞争端口db2.example.com的数据包。所以,您必须让db1.example.com的代理在另一个portlisten ,而不是在db2.example.com的代理上db2.example.com 。 否则nginx不知道如何路由数据包往返于两个上游。 道歉误解你原来的职位。 server_name不允许在stream定义中使用,因为与http头不同,tcp / udp数据包中没有额外的元数据标识哪个DNS用于将数据包定位到nginx。