温馨提示×

ubuntu nodejs怎样优化性能

小樊
47
2026-10-09 18:11:38
栏目: 编程语言

在 Ubuntu 上优化 Node.js 性能,可以从系统层面、Node.js 运行参数、代码层面、架构层面几个方向来做。下面给你一个比较实用、可落地的清单。


一、系统 & Ubuntu 层面优化

1. 使用最新 LTS 版本 Node.js

node -v

建议使用 Node.js 18 / 20 LTS(性能、V8 优化更好)

# 使用 NodeSource 安装
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

2. 调整文件描述符限制

Node.js 高并发时容易遇到:

EMFILE: too many open files
ulimit -n

临时:

ulimit -n 65535

永久(Ubuntu):

sudo vim /etc/security/limits.conf

添加:

* soft nofile 65535
* hard nofile 65535

3. 开启 TCP 优化(可选)

sudo sysctl -w net.core.somaxconn=65535
sudo sysctl -w net.ipv4.tcp_tw_reuse=1

二、Node.js 运行参数优化

1. 利用多核(Cluster / PM2)

Node.js 默认是单线程。

使用 PM2(推荐)

npm install -g pm2
pm2 start app.js -i max
pm2 startup
pm2 save

-i max 会按 CPU 核心数启动进程。


2. 调整 V8 内存(大内存应用)

node --max-old-space-size=4096 app.js

查看 CPU 核数:

nproc

3. 关闭不必要的调试

生产环境不要开启:

--inspect

三、代码层面优化(最重要)

1. 避免阻塞事件循环

❌ 错误:

const data = fs.readFileSync('big.json')

✅ 正确:

fs.readFile('big.json', (err, data) => {})

或使用 fs/promises


2. 使用流式处理大文件

fs.createReadStream('big.log')
  .pipe(transformStream)
  .pipe(res)

3. 缓存热点数据

  • Redis
  • 内存缓存(Map / LRU)
npm install lru-cache

4. 避免频繁 JSON.parse / 大对象

  • 拆分对象
  • 使用二进制(Buffer / Protocol Buffers)

四、Web 服务优化(Express / Koa / Fastify)

1. 使用更快的框架

性能排序(一般):

Fastify > Koa > Express

2. 开启 gzip / brotli

npm install compression

3. 静态资源交给 Nginx

Node.js 不适合直接服务静态文件。


五、Nginx + Node.js(强烈推荐)

location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
}

Nginx 负责:

  • 静态文件
  • gzip
  • 反向代理
  • 负载均衡

六、监控 & 性能分析

1. 查看 CPU / 内存

htop
pm2 monit

2. CPU Profile

node --prof app.js
node --prof-process isolate-*.log > result.txt

3. 使用 Clinic.js

npm install -g clinic
clinic doctor -- node app.js

七、常见性能瓶颈总结

问题 解决
单核 Cluster / PM2
阻塞 async / stream
内存泄漏 heap snapshot
静态慢 Nginx
高并发 缓存 + 限流

如果你愿意,可以告诉我:

  • 是 Web 服务 / API / 爬虫 / 计算任务
  • 当前 QPS / 内存占用
  • 用的框架(Express / Nest / Koa / 原生)

我可以给你针对性的优化方案。

0 踩