大网数据广告活动
服务器运维问答

How to proxy multiple tcp streams on one port with nginx

· 52CE 我爱测

With nginx http directive, you can have multiple servers on the same port with different names: server { listen 80; server_name server1.example.com; location / { proxy_pass http://server1.example.com; } } server { listen 80; serv…

问题原文

原帖链接 · joels · CC BY-SA 3.0

With nginx http directive, you can have multiple servers on the same port with different names:

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;
    }
}

Is it possible to have nginx proxy multiple mysql servers on the same port with different names like you can with http? They aren't part of a cluster or anything. The have different, unrelated tables.

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; }


}

社区高分解答

原帖链接 · 2ps · CC BY-SA 3.0

Yes, if nginx was compiled with --with-stream. https://www.nginx.com/resources/admin-guide/tcp-load-balancing/


Here is one of the examples with the same port:

upstream stream_backend {
    hash $remote_addr;

    server backend1.example.com:12345;
    server backend2.example.com:12345;
    server backend3.example.com:12346;
}

Second update:

You obviously can’t do anything like this:

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; }    
}

Because the nginx proxy for upstream db1.example.com is competing with db2.example.com for packets on port 3306. So you have to have the proxy for db1.example.com listening on another port than the proxy for db2.example.com. Otherwise nginx wouldn’t know how to route packets to and from the two upstreams. Apologies for misunderstanding your original post. server_name isn't allowed in stream definitions because, unlike http headers, there is no additional metadata in the tcp/udp packet that identifies which DNS was used to address the packet over to nginx.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-12-13)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。