在 CentOS 系统上,可以使用 Nginx 或 HAProxy 作为负载均衡器来实现 Node.js 应用程序的负载均衡。这里分别介绍如何使用这两种方法。
sudo yum install epel-release sudo yum install nginx
sudo systemctl start nginx sudo systemctl enable 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 应用程序实例的实际地址和端口。
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; } }
sudo nginx -t sudo systemctl reload nginx
现在,Nginx 将根据配置的负载均衡策略将请求分发到你的 Node.js 应用程序实例。
sudo yum install epel-release sudo yum install haproxy
sudo systemctl start haproxy sudo systemctl enable haproxy
/etc/haproxy/haproxy.cfg
),在 global
部分添加以下内容:global log /dev/log local0 log /dev/log local1 notice daemon
defaults
部分添加以下内容:defaults log global mode http option httplog option dontlognull timeout connect 5000ms timeout client 50000ms timeout server 50000ms
frontend
部分添加以下内容:frontend http_front bind *:80 stats uri /haproxy?stats default_backend http_back
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 应用程序实例的实际地址和端口。
sudo systemctl reload haproxy
现在,HAProxy 将根据配置的负载均衡策略将请求分发到你的 Node.js 应用程序实例。
这两种方法都可以实现 Node.js 应用程序的负载均衡。你可以根据自己的需求和喜好选择其中之一。