相對於LVS來說,Nginx做反向 Proxy工作在網路更高層(7層),但對於一般的負載平衡場合已足夠應付。若訪問量非常大或穩定性要求非常高的場合,選擇LVS還是有必要的。
本文力求用最簡的例子來示範如何使用Nginx做反向 Proxy實現負載平衡。
實現目標:用Nginx的80連接埠負載平衡本機8001和8002兩個http服務。
開始:
1、安裝Nginx。
不多說了,直接進入下一步,配置Nginx。
2、配置Nginx
修改nginx.conf設定檔
……upstream http_server_pool{ server 127.0.0.1:8001; server 127.0.0.1:8002;}server { listen 80; server_name localhost; location / { proxy_pass http://http_server_pool; proxy_set_header Host localhost; proxy_set_header X-Forwarded-For $remote_addr; } ……}
3、建立8001服務
這裡為了便捷,使用Python內建的SimpleHTTPServer來實現HTTP服務。
為了方便看出效果,建立一個a目錄,建立一個index.html檔案,直接輸出“This is 8001!”。
在a目錄下執行
python -m SimpleHTTPServer 8001
4、建立8002服務
(參照上一步)
5、運行Nginx
6、輪詢效果測試
訪問localhost,多刷幾次頁面,會發現有時輸出“This is 8001!”,有時是“This is 8002!”。
7、故障測試
手動分別把8001或8002服務停掉,訪問localhost會被引導到能夠正常工作的那一個服務上。
只要8001和8002沒有全停,服務均能通過80連接埠正常對外提供。
參考資料:
http://14shu.blogbus.com/logs/158759042.html
http://www.logo-printer.cn/blog/jishu/1299