在 Debian 上优化 Node.js 性能,通常从系统层、Node.js 运行参数、代码与架构、监控四个维度来做。下面给你一套比较实用的调优清单。
旧版 V8 性能差很多。
node -v
推荐:
nvm 或 nodesource 安装,不要用 apt 老版本curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs
Node 高并发时容易 EMFILE
ulimit -n
修改:
# /etc/security/limits.conf
* soft nofile 100000
* hard nofile 100000
# /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
sysctl -p
Node 默认单线程!
✅ 使用 Cluster:
const cluster = require('cluster');
或直接使用:
npm i pm2 -g
pm2 start app.js -i max
默认约 1.5–2G
node --max-old-space-size=4096 app.js
pm2:
pm2 start app.js --node-args="--max-old-space-size=4096"
node --optimize-for-size --jitless=false app.js
一般不建议手动改太多。
❌ 错误:
const data = fs.readFileSync()
✅ 正确:
fs.promises.readFile()
fs.createReadStream()
npm i lru-cache
fastify > expressnginx 而不是 Nodelocation / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
}
✅ 好处:
top
htop
node --prof app.js
node --inspect
npm i clinic
clinic doctor -- node app.js
| 问题 | 解决 |
|---|---|
| 单核 | cluster / pm2 |
| 阻塞 | async |
| 内存爆 | 限流 / 缓存 |
| 慢请求 | nginx |
| 老版本 | 升级 Node |
如果你愿意,可以告诉我:
我可以给你针对性配置。