溫馨提示×

Node.js 在 Linux 上如何實現負載均衡

小樊
35
2025-06-03 01:50:46
欄目: 云計算

在 Linux 上使用 Node.js 實現負載均衡,可以采用多種方法。以下是幾種常見的方法:

1. 使用 Nginx 作為反向代理

Nginx 是一個高性能的 HTTP 和反向代理服務器,可以用來分發請求到多個 Node.js 應用實例。

安裝 Nginx

sudo apt update
sudo apt install nginx

配置 Nginx

編輯 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf/etc/nginx/sites-available/default),添加以下內容:

http {
    upstream backend {
        server 127.0.0.1:3000;
        server 127.0.0.1:3001;
        server 127.0.0.1:3002;
    }

    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

2. 使用 HAProxy

HAProxy 是一個專業的負載均衡器和代理服務器,適用于高可用性和高性能的環境。

安裝 HAProxy

sudo apt update
sudo apt install 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 127.0.0.1:3000 check
    server node2 127.0.0.1:3001 check
    server node3 127.0.0.1:3002 check

重啟 HAProxy

sudo systemctl restart haproxy

3. 使用 Node.js 內置的 HTTP 模塊

Node.js 的內置 HTTP 模塊也可以用來實現簡單的負載均衡,但這種方法通常不推薦用于生產環境,因為它缺乏高級功能和穩定性。

const http = require('http');
const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxyServer({});

const servers = [
    { target: 'http://127.0.0.1:3000', weight: 1 },
    { target: 'http://127.0.0.1:3001', weight: 1 },
    { target: 'http://127.0.0.1:3002', weight: 1 }
];

let currentIndex = 0;

function getNextServer() {
    const server = servers[currentIndex];
    currentIndex = (currentIndex + 1) % servers.length;
    return server;
}

http.createServer((req, res) => {
    const server = getNextServer();
    proxy.web(req, res, { target: server.target });
}).listen(80);

總結

對于大多數生產環境,推薦使用 Nginx 或 HAProxy 來實現負載均衡,因為它們提供了更強大的功能和更好的性能。Node.js 內置的 HTTP 模塊可以用于開發和測試目的,但在生產環境中不推薦使用。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女