Nginx在1.9.0版本开始支持tcp模式的负载均衡,在1.9.13版本开始支持udp协议的负载,udp主要用于 DNS的域名解析,其配置方式和指令和http 代理类似,其基于ngx_stream_proxy_module模块实现tcp 负载,另外基于模块ngx_stream_upstream_module实现后端服务器分组转发、权重分配、状态监测、 调度算法等高级功能。
如果编译安装,需要指定 --with-stream 选项才能支持ngx_stream_proxy_module模块
官方文档:Module ngx_stream_proxy_module
一、TCP负载均衡配置参数
bash
stream { #定义stream相关的服务;
Context:main
upstream backend { #定义后端服务器
hash $remote_addr consistent; #定义调度算法
server backend1.example.com:12345 weight=5; #定义具体server
server 127.0.0.1:12345 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3;
}
upstream dns { #定义后端服务器
server 10.0.0.1:53; #定义具体server
server dns.example.com:53;
}
server { #定义server
listen 12345; #监听IP:PORT
proxy_connect_timeout 1s; #连接超时时间
proxy_timeout 3s; #转发超时时间
proxy_pass backend; #转发到具体服务器组
}
server {
listen 127.0.0.1:53 udp reuseport;
proxy_timeout 20s;
proxy_pass dns;
}
server {
listen [::1]:12345;
proxy_pass unix:/tmp/stream.socket;
}
}
二、负载均衡:MySQL
1、后端服务器安装MySQL
[root@apache20 ~]# yum install mariadb-server -y
[root@apache20 ~]# vim /etc/my.cnf.d/mariadb-server.cnf
[mysqld]
server-id=20
[root@apache20 ~]# systemctl start mariadb
[root@apache20 ~]# mysql -e "grant all on *.* to oqs@'%' identified by '123456';"
[root@apache30 ~]# mysql -uoqs -p123456 -h172.25.254.20 -e "select @@server_id"
[root@apache30 ~]# yum install mariadb-server -y[root@apache30 ~]# vim /etc/my.cnf.d/mariadb-server.cnf
[mysqld]
server-id=30
[root@apache30 ~]# systemctl start mariadb
[root@apache30 ~]# mysql -e "grant all on *.* to oqs@'%' identified by '123456';"
[root@apache30 ~]# mysql -uoqs -p123456 -h172.25.254.20 -e "select @@server_id"
2、nginx配置
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf

[root@Nginx ~]# vim /usr/local/nginx/conf/tcp/tcp.conf

重启nginx:nginx -s reload
3、测试

三、UDP负载均衡:DNS
1、nginx配置:
[root@Nginx ~]# vim /usr/local/nginx/conf/tcp/tcp.conf

重启nginx:nginx -s reload
2、后端做dns正向解析
[root@client ~]# vim /etc/named.rfc1912.zones

[root@client ~]# vim /var/named/qisheng.org.zone

两个后端服务器都要dns正向解析。
重启服务:systemctl restart named
3、测试

