一、nginx負載均衡說明
nginx僅僅是作爲NGINX PROXY反向代理使用的,因爲這個反向代理功能表現的效果是負載均衡,和真正的負載均衡還是有區別的。
負載均衡產品是轉發用戶的請求包,而nginx反向代理是接收用戶的請求然後重新發起請求區請求後面的節點。
實現nginx負載均衡的組件主要有兩個
ngx_http_proxy_module proxy代理模塊,用於請求後拋給服務器節點或upstream 服務器池
ngx_http_upstream_module 負載均衡模塊,可以實現網站的負載均衡功能及節點的健康檢查
二、配置說明:
使用3臺服務器,LB01作爲負載均衡器 ,web01和web02作爲網頁服務器
web01和web02的 主要配置如下
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_refere"' '"$http_user_agent" "$http_x_forwarded_for"'; server { listen 80; server_name bbs.hbgd.com; : location / { root html/bbs; index index.html index.htm; } access_log logs/access_bbs.log main; error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } server{ listen 80; server_name www.hbgd.com; location / { root html/www; index index.html index.htm; } access_log logs/access_www.log main; } }
說明,這裏做了個虛擬主機bbs.hbgd.com 和www.hbgd.com
然後編寫index主頁文件,如下所示:
然後檢查語法,重啓web01和web02的nginx服務
web01和 web02配置hosts文件後,相互測試
三、配置簡單的負載均衡
LB01的配置文件如下所示:
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服務器池,包含了兩個WEB節點 server 172.31.208.93:80 weight=1; #採用權重輪詢算法 server 172.31.208.94:80 weight=1; } server { #此處定義代理的負載均衡域名虛擬主機 listen 80; server_name www.hbgd.com; #charset koi8-r; #access_log logs/host.access.log main; location / { proxy_pass http://www_server_pools; #訪問www.hbgd.com 請求發送給www_server_pools裏面的節點 proxy_set_header Host $host; #在代理後端服務器發送的httpd請求頭中加入host字段信息,用於當後端服務器配置有多個虛擬主機時,可以識別代理 #的時哪個虛擬機主機,這是節點服務器多虛擬主機的關鍵配置 proxy_set_header X-Forwarded-For $remote_addr; #在代理向後端服務器發送的http請求頭部中加入X-Forwarde-for字段信息,用於後端服務器程序,日誌等接受記錄真實用戶的ip, #而不是代理服務器的IP include proxy.conf; #包含的配置 } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
檢查完成成後,重啓lb01上的nginx服務
然後再客戶端訪問www.hbgd.com,bbs.hbgd.com,可以看到每次訪問請求都會被分配到不同服務,權重算法生效