1. 程式人生 > >Nginx負載均衡4種方案

Nginx負載均衡4種方案

nginx配置 another 服務器 nginx負載均衡 address 第一個 session 添加 後端

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地址hars

前述的兩種負載均衡方案中,同一客戶端連續的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地址哈希的負載均衡可以組合在一起使用。

Nginx負載均衡4種方案