在CentOS上使用Node.js進行負載均衡,通常會結合反向代理服務器來實現。最常用的反向代理服務器是Nginx和HAProxy。以下是使用這兩種服務器進行負載均衡的基本步驟:
安裝Nginx:
sudo yum install epel-release
sudo yum install nginx
啟動并啟用Nginx服務:
sudo systemctl start nginx
sudo systemctl enable nginx
配置Nginx:
編輯Nginx配置文件(通常位于/etc/nginx/nginx.conf或/etc/nginx/conf.d/default.conf),添加負載均衡配置。例如:
http {
upstream backend {
server 192.168.1.1:3000;
server 192.168.1.2:3000;
server 192.168.1.3:3000;
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
重啟Nginx:
sudo systemctl restart nginx
安裝HAProxy:
sudo yum install haproxy
啟動并啟用HAProxy服務:
sudo systemctl start haproxy
sudo systemctl enable haproxy
配置HAProxy:
編輯HAProxy配置文件(通常位于/etc/haproxy/haproxy.cfg),添加負載均衡配置。例如:
global
log /dev/log local0
log /dev/log local1 notice
daemon
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
frontend http_front
bind *:80
default_backend http_back
backend http_back
balance roundrobin
server node1 192.168.1.1:3000 check
server node2 192.168.1.2:3000 check
server node3 192.168.1.3:3000 check
重啟HAProxy:
sudo systemctl restart haproxy
stick-table和stick on。通過以上步驟,你可以在CentOS上使用Nginx或HAProxy實現Node.js應用的負載均衡。