在 CentOS 上优化 Node.js,通常可以从 系统层面、Node.js 运行参数、代码与架构、监控与调优 四个方面来做。下面按实战角度整理一份较全面的优化指南。
yum update -y
如有条件,使用较新内核(3.10+,推荐 4.x/5.x)
Node.js 高并发时容易遇到:
EMFILE: too many open files
修改限制:
# 查看
ulimit -n
# 临时
ulimit -n 65535
# 永久
vi /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
vi /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 600
sysctl -p
推荐:
node -v
npm install -g pm2
pm2 start app.js -i max
好处:
如果不使用 PM2,可手动:
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
os.cpus().forEach(() => cluster.fork());
} else {
require('./app');
}
默认约 1.5G(老版本更小)
node --max-old-space-size=2048 app.js
PM2:
pm2 start app.js --node-args="--max-old-space-size=2048"
--optimize-for-size
--gc-interval=100
❌ 错误:
const data = fs.readFileSync('big.json');
✅ 正确:
fs.readFile('big.json', () => {});
fs.createReadStream('big.log')
.pipe(transform)
.pipe(res);
Promise.alllocation / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
}
好处:
Nginx:
gzip on;
gzip_types text/plain application/json;
top
htop
iostat
node --prof app.js
node --inspect
pm2 monit
pm2 dashboard
| 现象 | 原因 | 解决 |
|---|---|---|
| CPU 100% | 同步代码 / 死循环 | 异步化 |
| 内存暴涨 | 内存泄漏 | heapdump |
| QPS 低 | 单进程 | cluster / PM2 |
| 超时 | DB 慢 | 加索引 / 缓存 |
如果你愿意,可以告诉我:
我可以给你 针对性的优化方案。