2.5.Node + Nginx
Why Nginx?
負載均衡
負載均衡的目的是為了單個節點過大, 造成Web服務回應速度過慢, 嚴重導致服務癱瘓, 無法正常提供服務
Nginx
Nginx是一個負載均衡服務器(Load Balancer), 由Nginx前置頂住壓力, 後面多個node server完成業務支撑。
實現負載均衡常用的Web服務器有Nginx、HAProxy、LVS、Apache等
Nginx的內置負載策略 (Load Balance)
透過upstream模組來實現, 共有三種方式:
1.輪詢 (Round Robin): Nginx以事先定好的順序, 讓輪流server們輪流處理requset, 也是預設的分配方式
2.最少連結 (Least Connections): Request將會給當下連線數量最少的server
3.Ip-Hash/Sticky Sessions:綁定處理請求的服務器。第一次請求時, 根據客户端的IP算出一个HASH值, 將請求分配到集群中的某一台服務器上. 後面該客户端的所有請求, 都將透過HASH算法找到之前處理這台客户端請求的服务器, 然後將請求交给它来處理.
4.權重(Weight):
http { upstream node_server_pool { server 192.168.0.100:8080 weight=2; # 2/6次 server 192.168.0.101:8080 weight=3; # 3/6次 server 192.168.0.102:8080 weight=1; # 1/6次 } server{ listen 80; server_name localhost; location / { proxy_pass http://node_server_pool; } }
Install Nginx on Ubuntu 14.04 LTS
sudo apt-get update sudo apt-get install nginx
config balance loader
example
sudo nano /etc/nginx/nginx.conf worker_processes 1; events { worker_connections 1024; } http { upstream node_server_pool { server localhost:3001 max_fails=1; server localhost:3000 max_fails=1; } server{ listen 80; server_name localhost; location / { proxy_pass http://node_server_pool; } } }
config Nginx cahe server
config
# Expire rules for static content # cache.appcache, your document html and data location ~* \.(?:manifest|appcache|html?|xml|json)$ { expires -1; # access_log logs/static.log; # I don't usually include a static log } # Feed location ~* \.(?:rss|atom)$ { expires 1h; add_header Cache-Control "public"; } # Media: images, icons, video, audio, HTC location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ { expires 1M; access_log off; add_header Cache-Control "public"; } # CSS and Javascript location ~* \.(?:css|js)$ { expires 1y; access_log off; add_header Cache-Control "public"; }
check if cache control enable
reference
Last updated
Was this helpful?