Node.js在CentOS上如何实现高可用架构

133
2025/4/6 15:32:20
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在CentOS上使用Node.js实现高可用架构,通常涉及以下几个关键步骤和技术:

1. 负载均衡

负载均衡是将流量分发到多个服务器上,以提高系统的可用性和性能。常用的负载均衡器有Nginx、HAProxy等。

使用Nginx作为负载均衡器

  1. 安装Nginx

    sudo yum install nginx
    
  2. 配置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;
        }
    }
    
  3. 启动Nginx

    sudo systemctl start nginx
    sudo systemctl enable nginx
    

2. 集群模式

Node.js本身支持集群模式,可以利用多核CPU的优势。

使用Node.js内置的集群模块

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`);
}

3. 监控和自动故障转移

使用监控工具如Prometheus和Grafana来监控Node.js应用的性能,并设置自动故障转移。

使用PM2进行进程管理

PM2是一个进程管理器,可以帮助你管理和监控Node.js应用。

  1. 安装PM2

    sudo npm install pm2 -g
    
  2. 启动应用

    pm2 start app.js -i max
    
  3. 监控和管理

    pm2 monit
    pm2 logs
    pm2 restart app
    pm2 stop app
    

4. 数据库高可用

如果应用依赖数据库,确保数据库的高可用性。常用的数据库高可用方案有MySQL的主从复制、MongoDB的副本集等。

MySQL主从复制

  1. 配置主服务器: 编辑/etc/my.cnf,添加:

    [mysqld]
    server-id = 1
    log_bin = /var/log/mysql/mysql-bin.log
    
  2. 配置从服务器: 编辑/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
    
  3. 启动复制: 在主服务器上创建复制用户并授权:

    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;
    

5. 容器化和编排

使用Docker和Kubernetes进行容器化和编排,可以更方便地管理和扩展应用。

使用Docker

  1. 编写Dockerfile

    FROM node:14
    WORKDIR /usr/src/app
    COPY package*.json ./
    RUN npm install
    COPY . .
    EXPOSE 3000
    CMD ["node", "app.js"]
    
  2. 构建和运行容器

    docker build -t myapp .
    docker run -p 3000:3000 myapp
    

使用Kubernetes

  1. 编写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
    
  2. 部署到Kubernetes集群

    kubectl apply -f deployment.yaml
    

通过以上步骤,你可以在CentOS上实现一个高可用的Node.js架构。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: CentOS Sniffer如何过滤数据包