http://www.cnblogs.com/wunaozai/p/8278956.html
0. 前言
關於Nginx負載均衡的簡單配置,我以前博客配置過基於HTTP的負載均衡。這次的負載均衡有點不一樣,就是基於TCP的負載均衡。基於HTTP負載均衡是默認的Nginx版本支持的,配置也很簡單,但是基於TCP的負載均衡,配置起來就有一點點麻煩了。
1. 下載安裝
由於我們要用到四層TCP層負載均衡,所以要自己編譯Nginx,在這裏下載最新版 http://nginx.org/download/nginx-1.12.2.tar.gz 中間我們可能要進行調試一些參數,可以下載這個擴展 git clone https://github.com/openresty/echo-nginx-module
然後編譯
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
可能會要求安裝這個libgeoip-dev包 apt-get install libgeoip-dev 由於我只是需要用到裏面的geo擴展,不需要對應的信息,如果有需要的可以在這裏下載數據包http://dev.maxmind.com/geoip/legacy/downloadable/ https://www.cnblogs.com/kevingrace/p/6165572.html
當出現上圖信息,表示編譯成功
1 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 增加後重啓網卡
1 auto lo 2 iface lo inet loopback 3 4 auto eth1 5 iface eth1 inet static 6 address 172.16.23.204 7 netmask 255.255.255.0 8 gateway 172.16.23.1 9 10 #auto eth1:1 11 #iface eth1:1 inet static 12 # address 172.16.23.104 13 # netmask 255.255.255.0 14 # gateway 172.16.23.1
3. nginx.conf 配置文件
1 user root; 2 3 worker_processes auto; 4 5 events { 6 worker_connections 1024; 7 } 8 9 stream { 10 11 upstream backend { 12 server 172.16.20.217:60000; 13 server 172.16.20.217:60001; 14 } 15 16 upstream backbind { 17 server 172.16.23.203:54321; 18 } 19 20 map $msec $proxy_bind_ip { 21 ~[0-5]$ 172.16.23.111; 22 ~[5-9]$ 172.16.23.204; 23 } 24 25 server { 26 listen 12345; 27 proxy_pass backend; 28 proxy_bind $proxy_bind_ip; 29 } 30 } 31 32 http { 33 geo $LB { 34 default 1; 35 #include conf/geo.conf 36 172.16.20.217 0; 37 172.16.20.218 1; 38 } 39 map $LB $proxy_bind_ip { 40 0 172.16.23.111; 41 1 172.16.23.204; 42 } 43 map $msec $proxy_bind_ip_2 { 44 ~[0-5]$ 172.16.23.111; 45 ~[5-9]$ 172.16.23.204; 46 } 47 server { 48 listen 8888; 49 location /test { 50 echo $proxy_bind_ip; 51 echo $proxy_bind_ip_2; 52 echo $connection; 53 echo "hostname" $hostname; 54 echo "msec" $msec; 55 echo "pid" $pid; 56 echo "proxy_protocol" $proxy_protocol_addr ":" $proxy_protocol_port; 57 echo "remote:" $remote_addr ":" $remote_port; 58 echo "server:" $server_addr ":" $server_port; 59 echo "status:" $status; 60 echo "time:" $time_iso8601; 61 echo "time:" $time_local; 62 } 63 } 64 }
增加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