在 Debian 上优化 Node.js 通常可以从系统层面、Node 本身、运行方式、代码与依赖、监控几个维度来做。下面按实用优先级给你一个可操作的清单。
cat /etc/debian_version
uname -a
Node 是高并发 IO 程序,默认 1024 很容易崩。
ulimit -n
修改:
sudo vim /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
并确认:
/etc/pam.d/common-session
session required pam_limits.so
sudo vim /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15
sudo sysctl -p
推荐:
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo bash -
sudo apt install -y nodejs
✅ 推荐 Node 18 / 20 LTS
node --max-old-space-size=2048 app.js
常用:
--max-old-space-size=4096
--optimize-for-size
⚠️ 不要盲目加 --turbo
npm i -g pm2
pm2 start app.js -i max
pm2 save
pm2 startup
-i max 会按 CPU 核心数 fork
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
os.cpus().forEach(() => cluster.fork());
} else {
require('./app');
}
[Unit]
Description=Node App
After=network.target
[Service]
User=node
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/node app.js
Restart=always
[Install]
WantedBy=multi-user.target
❌ 避免:
✅ 使用:
fs.createReadStream('big.json')
.pipe(res)
而不是:
res.send(fs.readFileSync('big.json'))
gzip on;
gzip_types application/json text/plain;
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";
}
✅ Nginx 处理:
htop
iotop
netstat -ant | wc -l
node --inspect
pm2 monit
clinic doctor
clinic flame
| 现象 | 可能原因 |
|---|---|
| CPU 100% | 同步代码 / 正则 |
| 内存涨 | 闭包 / 缓存未清理 |
| 连接数上不去 | ulimit |
| 响应慢 | 数据库 / 外部 API |
| 随机卡死 | GC |
我可以给你针对性配置模板。