nginx的反向代理功能和負載均衡
阿新 • • 發佈:2018-04-30
ron break 技術 col charset 後臺 style one location
使用nginx實現反向代理
Nginx只做請求的轉發,後臺有多個http服務器提供服務,nginx的功能就是把請求轉發給後面的服務器,決定把請求轉發給誰。
1安裝tomcat
在一個虛擬機上創建兩個tomcat實例,模擬多個服務器。
2需求
通過訪問不同的域名訪問運行在不同端口的tomcat,適用於分布式部署
8080.tomcat.com 訪問運行8080端口的tomcat
8081.tomcat.com 訪問運行8081端口的tomcat
3域名需要配置host文件:
# vim /etc/hosts
4Nginx的配置
1 upstream tomcat1 { 2 server 127.0.0.1:8080; 3 } 4 upstream tomcat2 { 5 server 127.0.0.1:8081; 6 } 7 server { 8 listen 80; 9 server_name 8080.itheima.com; 10 11 #charset koi8-r; 12 13 #access_log logs/host.access.log main; 14 15 location / { 16 proxy_pass http://tomcat1; 17 index index.html index.htm; 18 } 19 20 21 } 22 server { 23 listen 80; 24 server_name 8081.itheima.com; 25 26 #charset koi8-r; 27 28 #access_log logs/host.access.log main; 29 30 location / { 31 proxy_pass http://tomcat2; 32 index index.html index.htm; 33 } 34 35 36 } 37
如果在同一個域名下有多臺服務器提供服務,此時需要nginx負載均衡。
只需要在一個upstream下添加服務機即可
置負載均衡的權重
在後邊添加:weight=x,x越大,被分配到請求的概率越大,如圖
-----------------------------------------------------------------------------------------------------------------------------------------
其他選項說明:
1 節點說明: 2 在http節點裏添加: 3 4 #定義負載均衡設備的 Ip及設備狀態 5 upstream myServer { 6 7 server 127.0.0.1:9090 down; 8 server 127.0.0.1:8080 weight=2; 9 server 127.0.0.1:6060; 10 server 127.0.0.1:7070 backup; 11 } 12 13 在需要使用負載的Server節點下添加 14 15 proxy_pass http://myServer; 16 17 upstream 每個設備的狀態: 18 19 down 表示單前的server暫時不參與負載 20 weight 默認為1.weight越大,負載的權重就越大。 21 max_fails :允許請求失敗的次數默認為1.當超過最大次數時,返回proxy_next_upstream 模塊定義的錯誤 22 fail_timeout:max_fails 次失敗後,暫停的時間。 23 backup: 其它所有的非backup機器down或者忙的時候,請求backup機器。所以這臺機器壓力會最輕。
nginx的反向代理功能和負載均衡