🎵負載均衡組件
ngx_http_upstream_module
https://nginx.org/en/docs/http/ngx_http_upstream_module.html
upstream模塊允許Nginx定義一組或多組節點服務器組,使用時可以通過多種方式去定義服務器組
樣例:
upstream backend {server backend1.example.com weight=5;server backend2.example.com:8080;server unix:/tmp/backend3;server backup1.example.com:8080 backup;server backup2.example.com:8080 backup;
}server {location / {proxy_pass http://backend;}
}
ngx_http_proxy_module
https://nginx.org/en/docs/http/ngx_http_proxy_module.html
樣例:
該ngx_http_proxy_module模塊允許將請求傳遞到另一臺服務器。
location / {proxy_pass http://localhost:8000;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;
}
🎶Nginx負載均衡配置實例
主機名 | IP | 角色 |
---|---|---|
NGINX-1 | 54.169.87.5 | NGINX服務器 |
NGINX-2 | 18.143.107.110 | NGINX服務器 |
NGINX-3 | 122.51.114.14 | NGINX負載均衡服務器 |
- 在兩臺NGINX服務器上操作,創建測試文件數據
echo "`hostname -I` " > /usr/share/nginx/html/index.html
- 配置NGINX負載均衡服務器,定義Web服務器池
upstream backend {server 18.143.107.110:80 weight=1;server 54.169.87.5:80 weight=1;}
location / {proxy_pass http://backend;
}
完整配置 nginx.conf
worker_processes 1;
events {worker_connections 1024;
}
http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;upstream backend { #這里定義Web服務器池server 18.143.107.110:80 weight=1; server 54.169.87.5:80 weight=1;}server { #這里定義代理的負載均衡域名虛擬主機listen 80;server_name www.nginxtestlb.com;location / {proxy_pass http://backend; #訪問www.nginxtestlb.com,請求發送給backend里面的節點}}
}
本地主機配置域名解析
C:\Windows\System32\drivers\etc\hosts
122.51.114.14 www.nginxtestlb.com
- 瀏覽器訪問
兩次訪問得出的信息不同,說明訪問的Nginx服務器已經實現負載均衡和反向代理