关于Nginx负载均衡的简单配置,我以前博客配置过基于HTTP的负载均衡。这次的负载均衡有点不一样,就是基于TCP的负载均衡。基于HTTP负载均衡是默认的Nginx版本支持的,配置也很简单,但是基于TCP的负载均衡,配置起来就有一点点麻烦了。
1. 下载安装
由于我们要用到四层TCP层负载均衡,所以要自己编译Nginx,在这里下载最新版 http://nginx.org/download/nginx-1.12.2.tar.gz 中间我们可能要进行调试一些参数
编译:
1. ./configure --prefix=/root/workspace/emq/nginx --with-stream --add-module=/root/workspace/emq/nginx-1.12.2/echo-nginx-module --with-http_geoip_module
.......
.......
2. make && make install
2. 增加虚拟网卡
一种是临时增加,一种是配置到开机启动
1 ifconfig eth1:1 172.16.23.111 netmask 255.255.255.0 up
2 ifconfig eth1:1 down
vim /etc/network/interfaces 增加后重启网卡
auto lo
iface lo inet loopback
auto eth1
iface eth1 inet static
address 172.16.23.204
netmask 255.255.255.0
gateway 172.16.23.1
#auto eth1:1
#iface eth1:1 inet static
# address 172.16.23.104
# netmask 255.255.255.0
# gateway 172.16.23.1
3. nginx.conf 配置文件
user root;
worker_processes auto;
events {
worker_connections 1024;
}
stream {
upstream backend {
server 172.16.20.217:60000;
server 172.16.20.217:60001;
}
upstream backbind {
server 172.16.23.203:54321;
}
map $msec $proxy_bind_ip {
~[0-5]$ 172.16.23.111;
~[5-9]$ 172.16.23.204;
}
server {
listen 12345;
proxy_pass backend;
proxy_bind $proxy_bind_ip;
}
}
http {
geo $LB {
default 1;
#include conf/geo.conf
172.16.20.217 0;
172.16.20.218 1;
}
map $LB $proxy_bind_ip {
0 172.16.23.111;
1 172.16.23.204;
}
map $msec $proxy_bind_ip_2 {
~[0-5]$ 172.16.23.111;
~[5-9]$ 172.16.23.204;
}
server {
listen 8888;
location /test {
echo $proxy_bind_ip;
echo $proxy_bind_ip_2;
echo $connection;
echo "hostname" $hostname;
echo "msec" $msec;
echo "pid" $pid;
echo "proxy_protocol" $proxy_protocol_addr ":" $proxy_protocol_port;
echo "remote:" $remote_addr ":" $remote_port;
echo "server:" $server_addr ":" $server_port;
echo "status:" $status;
echo "time:" $time_iso8601;
echo "time:" $time_local;
}
}
}
增加nginx的echo模块、geo模块、stream模块
一开始调试时,使用http{}进行调试,因为访问 http://127.0.0.1:8888/test 就可以进行变量调试了,以为不清楚map的语法,所以只能一点一点调试。
upstream {} 后端负载均衡器
map {} 变量映射
geo {} IP过滤等功能
server {} 服务器配置
更多功能这里不做描述,网上资料更多更全。
4. 测试
从上面两个图可以看到,创建两个服务监听应用
172.16.23.217:60000 172.16.23.217:60001 这两个模拟的是实际应用中的后端业务应用(MQTT集群)
TCP Client 创建5个连接,模拟不同客户端(MQTT设备)
172.16.23.204:12345 172.16.23.111:12345 这两个是负载均衡器Nginx监听的端口。
5个客户端连接连到Nginx负载均衡器,Nginx会随机负载到60000和60001两台后端应用服务,并且也会随机使用Nginx的虚拟网卡204或111