细说 Nginx: 负载均衡 Load Balance

细说 Nginx: 负载均衡 Load Balance

准备服务

首先我们先准备三个后端服务,起在 8081~8083 端口上

  • server.js
const express = require('express');

const createServer = (ports) => {
  const countMap = {}; // port => count

  ports.forEach((port, i) => {
    const id = i + 1;

    const app = express();

    let count = 0;
    app.get('/', (req, res) => {
      count += 1;
      countMap[id] = count;
      res.send({
        server: id,
        count: countMap,
      });
    });

    app.listen(port, () => {
      console.log(`server${id} listen on http://localhost:${port}`);
    });
  });
};

createServer([8081, 8082, 8083]);

我们使用 countMap 来记录每个服务响应请求的次数

负载均衡配置项

接下来是 nginx 的配置项,核心的指令是 upstream

http {
    upstream hello_server {
        server localhost:8081;
        server localhost:8082;
        server localhost:8083;
    }

    server {
        listen          8999;
        server_name     localhost;

        location / {
          proxy_pass  http://hello_server;
        }
    }
}

我们在 http 块里面添加 upstream 块,upstream 块内部再用 server 声明候选服务的域;最后再将 8999 代理到该服务上能够实现负载均衡

负载均衡策略

默认的情况下 nginx 采用轮询每个单体服务的方式,我们也可以指定负载策略

  • 最少连接数优先(least connection)
upstream hello_server {
    least_conn;

    # servers ...
}

改策略可以从连接数量上平衡请求

  • ip 映射
upstream hello_server {
    ip_hash;

    # servers ...
}

有些时候需要保证同一个 client 持续跟同一个 server 对接(可能使用 session 持久化等),这时候就使用 ip_hash 来保证多次连接使用同一个服务器

更多配置项

nginx 还提供了更多关于负载均衡的配置项,例如为 server 配置权重(weight)、server 的健康检查(失败次数限制 max_fails、超时检测 fail_timeout 等),需要用到再去配配看

传送门:Using nginx as HTTP load balancer - Health checks

示例

下面我们演示几个例子,直接使用上面的配置项并稍微做一点点的修改

ip_hash

upstream hello_server {
    ip_hash;

    server localhost:8081;
    server localhost:8082;
    server localhost:8083;
}

使用 ip_hash 之后我们可以看到多次请求之后一直都是同一个 server 被选中

轮询 + 权重

upstream hello_server {
    server localhost:8081 weight=3;
    server localhost:8082;
    server localhost:8083;
}

默认的轮询策略下同时为 server:8081 加上权重 3,可以看到连接的处理次数大致是其他服务的三倍


参考连接

TitleLink
Using nginx as HTTP load balancerhttps://nginx.org/en/docs/http/load_balancing.html

完整代码示例

https://github.com/superfreeeee/Blog-code/tree/main/deployment/nginx/nginx_detail_load_balancer

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值