nginx搭建負載均衡
阿新 • • 發佈:2018-11-13
負載均衡:針對web負載均衡簡單的說就是將請求通過負債均衡軟體或者負載均衡器將流量分攤到其它伺服器。
負載均衡的分類如下圖:
今天分享一下nginx實現負載均衡的實現,操作很簡單就是利用了nginx的反向代理和upstream實現:
伺服器名稱 | 地址 | 作用 |
A伺服器 | 192.168.0.212 | 負載均衡伺服器 |
B伺服器 | 192.168.0.213 | 後端伺服器 |
C伺服器 | 192.168.0.215 | 後端伺服器 |
A伺服器nginx配置如下:
1 upstream apiserver { 2 server 192.168.0.213:8081 weight=1 max_fails=2 fail_timeout=3; 3 server 192.168.0.215:8082 weight=1 max_fails=2 fail_timeout=3; 4 } 5 6 server { 7 listen 80; 8 server_name api.test.com;9 10 location / { 11 proxy_pass http://apiserver; 12 13 } 14 15 location ~ /\.ht { 16 deny all; 17 } 18 }
B伺服器配置如下:
1 server { 2 listen 8081; 3 server_name 192.168.0.213; 4 set $root_path '/data/wwwroot/Api/public/'; 5 root $root_path;6 index index.php index.html index.htm; 7 access_log /data/wwwlogs/access_log/api.8081.log; 8 try_files $uri $uri/ @rewrite; 9 location @rewrite { 10 rewrite ^/(.*)$ /index.php?_url=/$1; 11 } 12 13 location ~ \.php { 14 fastcgi_pass 127.0.0.1:9000; 15 fastcgi_index index.php; 16 include /usr/local/nginx/conf/fastcgi_params; 17 fastcgi_param PHALCON_ENV dev; 18 fastcgi_split_path_info ^(.+\.php)(/.+)$; 19 fastcgi_param PATH_INFO $fastcgi_path_info; 20 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 21 } 22 }
C伺服器配置如下:
server { listen 8082; server_name 192.168.0.215; set $root_path '/data/wwwroot/Api/public/'; root $root_path; index index.php index.html index.htm; access_log /data/wwwlogs/access_log/api.8081.log; try_files $uri $uri/ @rewrite; location @rewrite { rewrite ^/(.*)$ /index.php?_url=/$1; } location ~ \.php { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include /usr/local/nginx/conf/fastcgi_params; fastcgi_param PHALCON_ENV dev; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } }
到期負載均衡搭建完成,測試的可以訪問搭建的域名地址,然後在對應的後端伺服器列印access的log日誌進行檢視請求是否在輪詢伺服器。
思考:負載均衡搭建是搭建成功了,但是也有問題
1.這樣的架構會出現session無法共享的問題?
2.如果其中有一臺後端伺服器宕機了怎麼處理?
這些問題後面會有文章進行說明
.