Ngnix Proxy模塊的應用之負載均衡
Proxy 模塊介紹
在我之前的文章提到過,Nginx可以提供反向代理加速、基于應用層的負載均衡并能對后端
服務器做健康狀態檢測。下面我們就動手操作一下,看如何實現上述功能。
實驗環境
主機名稱 主要功能 外網地址 內網地址 code nginx代理服務器 192.168.1.11 192.168.10.1 node1 httpd應用服務器1 192.168.10.2 node2 httpd應用服務器2 192.168.10.3
如果之前沒有接觸過Nginx,請看我之前寫過的博文Nginx的編譯安裝。
配置Proxy
一、配置反向代理,并利用node1與node2實現負載均衡。
1.code上的配置,編輯配置文件
vim /usr/local/nginx/conf/nginx.conf
在主配置文件的http段使用upstream定義一個集群,后面的httpserver是集群的名稱。 upstream httpserver { server 192.168.10.2; server 192.168.10.3; } 之后在location / 中使用proxy_pass設置將用戶的所有請求全部代理到剛才定義好的負載均衡集群中。 location / { proxy_pass http://httpserver; root html; index index.html index.htm; }
啟動服務:[root@code ~]# /usr/local/nginx/sbin/nginx
重啟服務:[root@code ~]# /usr/local/nginx/sbin/nginx -s reload2.node1上的配置
[root@node1 ~]# yum install httpd -y 安裝httpd
[root@node1 ~]# service httpd start 啟動httpd服務
[root@node1 ~]# echo “This is node1 page” > /var/www/html/index.html 定義一個主頁面。3.node2上的配置
[root@node2 ~]# yum install httpd -y 安裝httpd
[root@node2 ~]# service httpd start 啟動httpd服務
[root@node2 ~]# echo “This is node2 page” > /var/www/html/index.html 定義一個主頁面。配置不同的頁面,方便我們區分。4.打開瀏覽器輸入代理服務器的地址192.168.1.11進行測試:
可以看到成功的進行了負載均衡。
5.將node2上面的httpd服務停掉,進行測試。
[root@node2 ~]# service httpd stop
代理服務器檢測到了node2的健康狀態不正常,則后續的請求全部發給了node1進行響應。
6.將node2上面的httpd服務啟動,再進行測試。
[root@node2 ~]# service httpd start
在代理服務器檢測到node2的健康狀態正常后,又將用戶的請求負載至兩臺node上。
原創文章,作者:張小凡,如若轉載,請注明出處:http://www.www58058.com/13536
哈哈,動圖盡顯專業,用心在寫文章。鑒定完畢,贊!