9.1 Stream Context
Problem
You need to distribute load between two or more UDP servers.
问题
需要在多台 UDP 服务器间实现负载均衡
Solution
Use NGINX’s stream module to load balance over UDP servers
using the upstream block defined as udp:
stream {
upstream ntp {
server ntp1.example.com:123 weight=2;
server ntp2.example.com:123;
}
server {
listen 123 udp;
proxy\_pass ntp;
}
}
This section of configuration balances load between two upstream
NTP servers using the UDP protocol. Specifying UDP load balanc‐
ing is as simple as using the udp parameter on the listen directive.
解决方案
NGINX stream 模块实现 UDP 服务器的负载均衡,作为 UDP 服务器的代理的
upstream 块级指令被定义称使用 UDP 协议:
stream {
upstream ntp {
server ntp1.example.com:123 weight=2;
server ntp2.example.com:123;
}
server {
listen 123 udp;
proxy\_pass ntp;
}
}
示例中,对 2 台使用 UDP 协议的 NTP 服务器进行负载均衡代理。实现 UDP 协议
的负载均衡,简单到仅需在 server 指令块中的 listen 指令加上一个 udp
参数就可以了。
Discussion
One might ask, “Why do you need a load balancer when you can
have multiple hosts in a DNS A or SRV record?” The answer is that
not only are there alternative balancing algorithms we can balance
with, but we can load balance over the DNS servers themselves.
UDP services make up a lot of the services that we depend on in
networked systems such as DNS, NTP, and Voice over IP. UDP load
balancing may be less common to some but just as useful in the
world of scale.
UDP load balancing will be found in the stream module, just like
TCP, and configured mostly in the same way. The main difference is
that the listen directive specifies that the open socket is for work‐
ing with datagrams. When working with datagrams, there are some
other directives that may apply where they would not in TCP, such
as the proxy_response directive that tells NGINX how many
expected responses may be sent from the upstream server, by default
being unlimited until the proxy_timeout limit is reached.
结论
或许有人会问 “既然有多条 A 记录或 SRV 记录的 DNS 域名解析,为什么我
还需要使用 NGINX 的负载均衡功能呢?” 我们的理由是,NGINX 不仅提供了
多种负载均衡算法,而且还能对 DNS 服务器本身进行负载均衡处理。UDP 协
议构建了 DNS 解析、NTP 服务器、IP 语音服务等大量基础服务。UDP 负载
均衡在某些场景下运用不是特别广泛,但在整个网络世界则并非如此。
UDP 负载均衡同 TCP 负载均衡一样集成在 stream 模块内,并且它们的使用
方法也几乎一样。二者的主要区别是,在 listen 指令中定义用于 UDP 协议
的套接字及 udp 参数。此外,还有一些仅用于 UDP 协议的指令,像
proxy_response 指令,proxy_response 指令告知 NGINX 服务器从被代理服
务器接收多少预期响应,默认是无限制的,直到达到 proxy_timeout 设定值。