1、輪詢
輪詢即Round Robin,根據Nginx配置文件中的順序,依次把客戶端的Web請求分發到不同的后端服務器。
配置的例子如下:
- http{
- upstream sampleapp {
- server <<dns entry or IP Address(optional with port)>>;
- server <<another dns entry or IP Address(optional with port)>>;
- }
- ....
- server{
- listen 80;
- ...
- location / {
- proxy_pass http://sampleapp;
- }
- }
上面只有1個DNS入口被插入到upstream節,即sampleapp,同樣也在后面的proxy_pass節重新提到。
2、最少連接
Web請求會被轉發到連接數最少的服務器上。
配置的例子如下:
- http{
- upstream sampleapp {
- least_conn;
- server <<dns entry or IP Address(optional with port)>>;
- server <<another dns entry or IP Address(optional with port)>>;
- }
- ....
- server{
- listen 80;
- ...
- location / {
- proxy_pass http://sampleapp;
- }
- }
上面的例子只是在upstream節添加了least_conn配置。其它的配置同輪詢配置。
3、IP地址哈希
前述的兩種負載均衡方案中,同一客戶端連續的Web請求可能會被分發到不同的后端服務器進行處理,因此如果涉及到會話Session,那么會話會比較復雜。常見的是基于數據庫的會話持久化。要克服上面的難題,可以使用基于IP地址哈希的負載均衡方案。這樣的話,同一客戶端連續的Web請求都會被分發到同一服務器進行處理。
配置的例子如下:
- http{
- upstream sampleapp {
- ip_hash;
- server <<dns entry or IP Address(optional with port)>>;
- server <<another dns entry or IP Address(optional with port)>>;
- }
- ....
- server{
- listen 80;
- ...
- location / {
- proxy_pass http://sampleapp;
- }
- }
上面的例子只是在upstream節添加了ip_hash配置。其它的配置同輪詢配置。
4、基于權重的負載均衡
基于權重的負載均衡即Weighted Load Balancing,這種方式下,我們可以配置Nginx把請求更多地分發到高配置的后端服務器上,把相對較少的請求分發到低配服務器。
配置的例子如下:
- http{
- upstream sampleapp {
- server <<dns entry or IP Address(optional with port)>> weight=2;
- server <<another dns entry or IP Address(optional with port)>>;
- }
- ....
- server{
- listen 80;
- ...
- location / {
- proxy_pass http://sampleapp;
- }
- }
上面的例子在服務器地址和端口后weight=2的配置,這意味著,每接收到3個請求,前2個請求會被分發到第一個服務器,第3個請求會分發到第二個服務器,其它的配置同輪詢配置。
還要說明一點,基于權重的負載均衡和基于IP地址哈希的負載均衡可以組合在一起使用。