在Debian上部署Node.js集群可以通過多種方式實現,以下是一個基本的方案,使用PM2(Process Manager 2)來管理和部署Node.js應用。
在所有節點上安裝Node.js和npm。你可以使用NodeSource的二進制分發庫來安裝最新版本的Node.js。
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
在所有節點上安裝PM2。
sudo npm install pm2 -g
使用PM2的集群模式來啟動你的Node.js應用。假設你的應用入口文件是app.js
。
pm2 start app.js -i max
-i max
參數會根據CPU核心數自動啟動相應數量的實例。
你可以創建一個PM2配置文件(例如ecosystem.config.js
)來更詳細地配置你的集群。
module.exports = {
apps: [{
name: 'my-app',
script: 'app.js',
instances: 'max', // or a number of instances
exec_mode: 'cluster',
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production'
}
}]
};
然后使用PM2啟動配置文件:
pm2 start ecosystem.config.js --env production
如果你有多個Node.js實例,可以使用Nginx或HAProxy來配置負載均衡。
sudo apt-get install nginx
編輯/etc/nginx/sites-available/default
文件,添加以下內容:
upstream my-app {
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://my-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 systemctl restart nginx
sudo apt-get install 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
sudo systemctl restart haproxy
通過以上步驟,你可以在Debian上使用PM2和Nginx或HAProxy來部署和管理Node.js集群。這樣可以確保你的應用在高可用性和負載均衡方面表現良好。