1.反向代理與負載均衡概念簡介
嚴格地說, nginx僅僅是做爲 Nginx Proxy反向代理使用的,由於這個反向代理功能表現的效果是負載均衡集羣的效果,因此本文稱之爲nginx負載均衡。那麼,反向代理和負載均衡有什麼區別呢?
普通負載均衡軟件,例如大名鼎鼎的LVS,其實現的功能只是對請求數據包的轉發(也可能會改寫數據包)、傳遞,其中DR模式明顯的特徵是從負載均衡下面的節點服務器來看,接收到的請求仍是來自訪問負載均衡器的客戶端的真實用戶,而反向代理就不樣了,反向代理接收訪問用戶的請求後,會代理用戶從新發起請求代理下的節點服務器,最後把數據返回給客戶端用戶,在節點服務器看來,訪問的節點服務器的客戶端用戶就是反向代理服務器了,而非真實的網站訪問用戶。句話,LVS等的負載均衡是轉發用戶請求的數據包,而 nginx反向代理是接收用戶的請求而後從新發起請求去請求其後面的節點。html
二、實現負載均衡的組件說明:nginx
實現負載均衡的組件主要有兩個:web
ngx_http_proxy_module proxy代理模塊,用於把請求後拋給服務器節點或upstream服務器池 ngx_http_upstream_module 負載均衡模塊,能夠實現網站的負載均衡功能及結點的健康檢查
系統:CentOS Linux release 7.5.1804 (Core)
LB01 192.168.100.105 nginx主負載均衡器
LB02 192.168.100.106 nginx輔負載均衡器
Web01 192.168.100.107 Web01服務器
Web02 192.168.100.108 Web02服務器
nginx版本:1.8.1
3、安裝nginx軟件
在以上4臺服務器上安裝nginx服務器
編譯安裝nginx請參考:https://www.cnblogs.com/Mr-Ding/p/9502529.htmlapp
nginx啓動腳本參考:https://www.cnblogs.com/Mr-Ding/p/9502972.html負載均衡
nginx web01和web02配置以下:curl
cat nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } access_log logs/access.log main; } } 重啓服務: systemctl reload nginx web01下面寫入: [root@web01 conf]# echo "192.168.100.107" > ../html/index.html web02下面寫入: [root@web02 conf]# echo "192.168.100.108" > ../html/index.html 配置hosts: web01: [root@web01 conf]# tail -1 /etc/hosts 192.168.100.107 www.dmtest.com web02: [root@web02 conf]# tail -1 /etc/hosts 192.168.100.108 www.dmtest.com 測試: [root@web01 conf]# curl www.dmtest.com 192.168.100.107 [root@web02 conf]# curl www.dmtest.com 192.168.100.108
在LB01上做以下操做: [root@lb01 conf]# cat nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream www_server_pools { #這裏是定義web服務器池,包含了107和108兩個web節點; server 192.168.100.107:80 weight=1; server 192.168.100.108:80 weight=1; } server { #這裏是定義代理的負載均衡域名虛擬主機; listen 80; server_name www.dmtest.com; location / { proxy_pass http://www_server_pools; #訪問www.dmtest.com,請求發送給www_server_pools裏面的節點; } } } 檢查語法並重啓nginx服務 [root@lb01 conf]# ../sbin/nginx -t nginx: the configuration file /application/nginx-1.8.1/conf/nginx.conf syntax is ok nginx: configuration file /application/nginx-1.8.1/conf/nginx.conf test is successful [root@lb01 conf]# systemctl restart nginx 測試: [root@lb01 conf]# tail -1 /etc/hosts 192.168.100.105 www.dmtest.com [root@lb01 conf]# curl www.dmtest.com 192.168.100.107 [root@lb01 conf]# curl www.dmtest.com 192.168.100.108 [root@lb01 conf]# curl www.dmtest.com 192.168.100.107 [root@lb01 conf]# curl www.dmtest.com 192.168.100.108