Nginx 提供了以下三種 load balancing 方法
- round-robin:預設值,會將請留輪流平均分配到每台伺服器上
- lest-connected:會將請求分配到目前連接數最少的伺服器上
- ip-hash:利用 hash-function 來決定使用者要被分配到的伺服器,此方法可以達到同一個使用者 (IP address) 每次連結的伺服器都是相同的
實作環境
Load Balancer
IP:192.168.0.1
Web Server 1
IP:192.168.0.2
Web Server 2
IP:192.168.0.3
Web Server 設定
server {
listen 80;
server_name {server_name};
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
Load Balancer 設定
upstream balancer {
server 192.168.0.2 weight=3;
server 192.168.0.3 weight=2;
}
server {
listen 443 ssl;
server_name {server_name};
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
ssl_certificate {ssl_certificate};
ssl_certificate_key {ssl_certificate_key};
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
location / {
proxy_pass http://balancer;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
Host 設定
vi /etc/nginx/conf.d/default.conf
{server_name} 192.168.0.2
{server_name} 192.168.0.3
No Comment!
Join Us Discuss