在CentOS上使用Node.js實現高可用架構,通常涉及以下幾個關鍵步驟和技術:
負載均衡是將流量分發到多個服務器上,以提高系統的可用性和性能。常用的負載均衡器有Nginx、HAProxy等。
安裝Nginx:
sudo yum install nginx
配置Nginx:
編輯/etc/nginx/nginx.conf
或創建一個新的配置文件在/etc/nginx/conf.d/
目錄下,例如myapp.conf
。
upstream myapp {
server 192.168.1.1:3000;
server 192.168.1.2:3000;
server 192.168.1.3:3000;
}
server {
listen 80;
server_name myapp.example.com;
location / {
proxy_pass http://myapp;
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 start nginx
sudo systemctl enable nginx
Node.js本身支持集群模式,可以利用多核CPU的優勢。
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
使用監控工具如Prometheus和Grafana來監控Node.js應用的性能,并設置自動故障轉移。
PM2是一個進程管理器,可以幫助你管理和監控Node.js應用。
安裝PM2:
sudo npm install pm2 -g
啟動應用:
pm2 start app.js -i max
監控和管理:
pm2 monit
pm2 logs
pm2 restart app
pm2 stop app
如果應用依賴數據庫,確保數據庫的高可用性。常用的數據庫高可用方案有MySQL的主從復制、MongoDB的副本集等。
配置主服務器:
編輯/etc/my.cnf
,添加:
[mysqld]
server-id = 1
log_bin = /var/log/mysql/mysql-bin.log
配置從服務器:
編輯/etc/my.cnf
,添加:
[mysqld]
server-id = 2
relay_log = /var/log/mysql/mysql-relay-bin.log
log_bin = /var/log/mysql/mysql-bin.log
read_only = 1
啟動復制: 在主服務器上創建復制用戶并授權:
CREATE USER 'replicator'@'%' IDENTIFIED BY 'password';
GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%';
FLUSH PRIVILEGES;
在從服務器上設置主服務器信息:
CHANGE MASTER TO
MASTER_HOST='master_ip',
MASTER_USER='replicator',
MASTER_PASSWORD='password',
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=107;
START SLAVE;
使用Docker和Kubernetes進行容器化和編排,可以更方便地管理和擴展應用。
編寫Dockerfile:
FROM node:14
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
構建和運行容器:
docker build -t myapp .
docker run -p 3000:3000 myapp
編寫Kubernetes部署文件:
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myapp:latest
ports:
- containerPort: 3000
部署到Kubernetes集群:
kubectl apply -f deployment.yaml
通過以上步驟,你可以在CentOS上實現一個高可用的Node.js架構。