在 Ubuntu 上优化 Node.js 性能,可以从系统层面、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
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
sudo sysctl -w net.core.somaxconn=65535
sudo sysctl -w net.ipv4.tcp_tw_reuse=1
Node.js 默认是单线程。
npm install -g pm2
pm2 start app.js -i max
pm2 startup
pm2 save
-i max 会按 CPU 核心数启动进程。
node --max-old-space-size=4096 app.js
查看 CPU 核数:
nproc
生产环境不要开启:
--inspect
❌ 错误:
const data = fs.readFileSync('big.json')
✅ 正确:
fs.readFile('big.json', (err, data) => {})
或使用 fs/promises
fs.createReadStream('big.log')
.pipe(transformStream)
.pipe(res)
npm install lru-cache
性能排序(一般):
Fastify > Koa > Express
npm install compression
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 负责:
htop
pm2 monit
node --prof app.js
node --prof-process isolate-*.log > result.txt
npm install -g clinic
clinic doctor -- node app.js
| 问题 | 解决 |
|---|---|
| 单核 | Cluster / PM2 |
| 阻塞 | async / stream |
| 内存泄漏 | heap snapshot |
| 静态慢 | Nginx |
| 高并发 | 缓存 + 限流 |
如果你愿意,可以告诉我:
我可以给你针对性的优化方案。