centos

CentOS 系统 Node.js 怎么进行负载均衡

小樊
49
2025-06-24 09:30:59
栏目: 云计算

在 CentOS 系统上,可以使用 Nginx 或 HAProxy 作为负载均衡器来实现 Node.js 应用程序的负载均衡。这里分别介绍如何使用这两种方法。

使用 Nginx 进行负载均衡

  1. 首先,确保已经安装了 Nginx。如果没有,请运行以下命令安装:
sudo yum install epel-release
sudo yum install nginx
  1. 启动 Nginx 服务并设置开机启动:
sudo systemctl start nginx
sudo systemctl enable nginx
  1. 编辑 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf),在 http 部分添加一个新的 upstream 块,列出你的 Node.js 应用程序实例:
http {
    upstream node_app {
        server 192.168.1.1:3000;
        server 192.168.1.2:3000;
        server 192.168.1.3:3000;
    }
    
    ...
}

将 IP 地址和端口替换为你的 Node.js 应用程序实例的实际地址和端口。

  1. server 块中,配置 Nginx 代理设置,将请求转发到 upstream 块中定义的 Node.js 应用程序实例:
server {
    listen 80;

    location / {
        proxy_pass http://node_app;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
  1. 保存更改并重新加载 Nginx 配置:
sudo nginx -t
sudo systemctl reload nginx

现在,Nginx 将根据配置的负载均衡策略将请求分发到你的 Node.js 应用程序实例。

使用 HAProxy 进行负载均衡

  1. 首先,确保已经安装了 HAProxy。如果没有,请运行以下命令安装:
sudo yum install epel-release
sudo yum install haproxy
  1. 启动 HAProxy 服务并设置开机启动:
sudo systemctl start haproxy
sudo systemctl enable haproxy
  1. 编辑 HAProxy 配置文件(通常位于 /etc/haproxy/haproxy.cfg),在 global 部分添加以下内容:
global
    log /dev/log local0
    log /dev/log local1 notice
    daemon
  1. defaults 部分添加以下内容:
defaults
    log global
    mode http
    option httplog
    option dontlognull
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms
  1. frontend 部分添加以下内容:
frontend http_front
    bind *:80
    stats uri /haproxy?stats
    default_backend http_back
  1. backend 部分添加以下内容,列出你的 Node.js 应用程序实例:
backend http_back
    balance roundrobin
    server node_app1 192.168.1.1:3000 check
    server node_app2 192.168.1.2:3000 check
    server node_app3 192.168.1.3:3000 check

将 IP 地址和端口替换为你的 Node.js 应用程序实例的实际地址和端口。

  1. 保存更改并重新加载 HAProxy 配置:
sudo systemctl reload haproxy

现在,HAProxy 将根据配置的负载均衡策略将请求分发到你的 Node.js 应用程序实例。

这两种方法都可以实现 Node.js 应用程序的负载均衡。你可以根据自己的需求和喜好选择其中之一。

0
看了该问题的人还看了