講講Nginx如何實現四層負載均衡

2021-10-09 08:58:05 字數 2754 閱讀 2259

這次又被問到nginx四層負載均衡的問題了,別慌,我們一起來細細分析這個看似簡單的問題。

負載均衡可以分為靜態負載均衡和動態負載均衡,接下來,我們就一起來分析下nginx如何實現四層靜態負載均衡和四層動態負載均衡。

nginx的四層靜態負載均衡需要啟用ngx_stream_core_module模組,預設情況下,ngx_stream_core_module是沒有啟用的,需要在安裝nginx時,新增--with-stream配置引數啟用,如下所示。

./configure --prefix=/usr/local/nginx-1.17.2 --with-openssl=/usr/local/src/openssl-1.0.2s --with-pcre=/usr/local/src/pcre-8.43 --with-zlib=/usr/local/src/zlib-1.2.11 --with-http_realip_module --with-http_stub_status_module --with-http_ssl_module --with-http_flv_module --with-http_gzip_static_module --with-cc-opt=-o3 --with-stream  --with-http_ssl_module
配置http負載均衡時,都是配置在http指令下,配置四層負載均衡,則是在stream指令下,結構如下所示.

stream  server }
upstream mysql_backend
server
配置完之後,就可以連線nginx的3307埠,訪問資料庫了。

完整的nginx配置如下:

user  hadoop hadoop;worker_processes  auto; error_log  logs/error.log;#error_log  logs/error.log  notice;#error_log  logs/error.log  info; #pid        logs/nginx.pid;  events  stream  server }
配置nginx四層靜態負載均衡後,重啟nginx時,worker程序一直不退出,會報錯,如下所示。

nginx: worker process is shutting down;
這是因為worker程序維持的長連線一直在使用,所以無法退出,只能殺掉程序。可以使用nginx的四層動態負載均衡解決這個問題。

使用nginx的四層動態負載均衡有兩種方案:使用商業版的nginx和使用開源的nginx-stream-upsync-module模組。注意:四層動態負載均衡可以使用nginx-stream-upsync-module模組,七層動態負載均衡可以使用nginx-upsync-module模組。

使用如下命令為nginx新增nginx-stream-upsync-module模組和nginx-upsync-module模組,此時,nginx會同時支援四層動態負載均衡和http七層動態負載均衡。

git clone  clone  clone  -r nginx-stream-upsync-module/* nginx-upsync/nginx-stream-upsync-module/cp -r nginx-upsync-module/* nginx-upsync/nginx-upsync-module/ ./configure --prefix=/usr/local/nginx-1.17.2 --with-openssl=/usr/local/src/openssl-1.0.2s --with-pcre=/usr/local/src/pcre-8.43 --with-zlib=/usr/local/src/zlib-1.2.11 --with-http_realip_module --with-http_stub_status_module --with-http_ssl_module --with-http_flv_module --with-http_gzip_static_module --with-cc-opt=-o3 --with-stream --add-module=/usr/local/src/nginx-upsync --with-http_ssl_module
配置http負載均衡時,都是配置在http指令下,配置四層負載均衡,則是在stream指令下,結構如下所示,

stream  server }
upstream mysql_backend
server
curl -x put -d ""  -x put -d ""
curl -x delete
server
配置upstream_show指令後,可以通過curl 檢視當前動態負載均衡上游伺服器列表。

nginx的完整配置如下:

user  hadoop hadoop;worker_processes  auto; error_log  logs/error.log;#error_log  logs/error.log  notice;#error_log  logs/error.log  info; #pid        logs/nginx.pid;  events  stream  server  server }

Nginx 四層負載均衡

目錄四層負載均衡是基於ip 埠的負載均衡,七層負載均衡是基於url或主機名等應用層資訊的負載均衡。其他層負載均衡 載 二層負載均衡 mac 一般是用虛擬mac位址方式,外部對虛擬的mac位址請求,負載均衡接收後分配後端真實的mac位址響應。三層負載均衡 ip 一般採用虛擬ip位址方式,外部對虛擬的i...

Nginx四層負載均衡概述

目錄nginx如何配置四層負載均衡 nginx四層負載均衡埠 四層負載均衡是基於傳輸層協議包來封裝的 如 tcp ip 那我們前面使用到的七層是指的應用層,他的組裝在四層的基礎之上,無論四層還是七層都是指的osi網路模型。1 四層 七層來做負載均衡,四層可以保證七層的負載均衡的高可用性 如 ngin...

Nginx 四層負載均衡配置

nginx1.9之後,開始支援四層負載均衡,需要引入額外的模組 測試環境 centos7 nginx1.9開始支援tcp層的 通過stream實現的,而socket也是基於tcp通訊。wget 作用 實現反向 負載負載庫wget tar zxvf master nginx 支援tcp 和負載均衡的支...