想让Node.js应用在Linux上跑得更快、更稳?集群部署是个好办法,它能把多核CPU的性能真正榨干。下面就来一步步拆解这个过程,从零开始,把集群跑起来。

Node.js在Linux上的集群部署

1. 安装Node.js

先把基础打好——确保系统里装上了Node.js。如果还没装,直接从官方源拉一份,或者用NodeSource的脚本一键搞定。

# 使用NodeSource安装Node.js
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs

2. 创建Node.js应用程序

假设你已经有个现成的应用,或者先写个简单的练练手。下面这个就是最基础的HTTP服务,监听3000端口,返回一句“Hello World”。

// app.js
const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200);
  res.end('Hello World\n');
});
server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

3. 使用Node.js集群模块

Node.js自带的cluster模块就是干这个的——它能创建多个工作进程,所有进程共享同一个端口,实现负载均衡。核心逻辑很简单:主进程负责fork出子进程,每个子进程都跑同样的HTTP服务。

// cluster-app.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(3000);

  console.log(`Worker ${process.pid} started`);
}

4. 运行集群应用程序

直接运行刚才那个文件,就能看到主进程和多个工作进程同时启动。

node cluster-app.js

5. 使用PM2进行进程管理

手动管理进程总归不便,这时候PM2就该出场了。它不仅是进程守护,还能自动重启、日志管理,甚至帮你做负载均衡。

安装PM2

sudo npm install pm2 -g

启动应用程序

pm2 start启动,加个-i max参数,PM2会自动根据CPU核心数创建工作进程,省心又省力。

pm2 start cluster-app.js -i max

查看应用程序状态

随时查看进程状态和实时日志,对排查问题非常有用。

pm2 status
pm2 logs

停止应用程序

pm2 stop cluster-app

重启应用程序

pm2 restart cluster-app

6. 配置Nginx作为反向袋里

到了生产环境,通常还会在Node.js前面加一层Nginx,做反向袋里。这样既能提升安全性,又能利用Nginx的静态文件处理、缓存等能力。

安装Nginx

sudo apt-get update
sudo apt-get install nginx

配置Nginx

编辑Nginx的配置文件(一般位于/etc/nginx/sites-a vailable/default),把请求转发到Node.js的3000端口。

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        proxy_pass http://localhost:3000;
        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;
    }
}

重启Nginx

sudo systemctl restart nginx

至此,你的Node.js集群应用已经通过Nginx对外提供服务了。整个流程走下来,从单进程到多进程,再到进程管理和反向袋里,一个生产级部署方案就成型了。

本文转载于:https://www.yisu.com/ask/97552965.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。