在 Debian 系统下优化 Node.js,通常可以从 系统层面、Node.js 运行参数、代码与架构、以及运维监控 四个方面入手。下面给你一套比较实用的优化方案(适用于生产环境)。
Debian 自带源中的 Node.js 版本通常较旧,建议用 NodeSource 或 nvm 安装 LTS 版本。
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
验证:
node -v
npm -v
Node.js 高并发时容易遇到文件描述符不足。
ulimit -n
建议设置为:
ulimit -n 65535
永久生效(Debian):
sudo vim /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
编辑:
sudo vim /etc/sysctl.conf
添加:
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
生效:
sudo sysctl -p
Node.js 默认内存较小(约 1.5–2 GB)。
node --max-old-space-size=4096 app.js
常见值:
Node.js 默认单线程,必须利用多核。
npm install -g pm2
pm2 start app.js -i max
pm2 save
pm2 startup
-i max 会自动使用 CPU 核心数。
export NODE_ENV=production
或在 PM2 中:
pm2 start app.js --node-args="--max-old-space-size=4096" -i max
❌ 避免:
✅ 使用:
setImmediateworker_threadsnpm prune --production
避免:
upstream nodeapp {
server 127.0.0.1:3000;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://nodeapp;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
✅ 好处:
top
htop
pm2 monit
pm2 logs
clinic.js0xnode --prof| 问题 | 解决方案 |
|---|---|
| CPU 100% | 优化算法 / worker_threads |
| 内存暴涨 | 泄漏排查 / 限制内存 |
| 并发上不去 | Nginx + PM2 |
| 响应慢 | 异步化 / 缓存 |
| 崩溃 | PM2 自动重启 |
✅ Debian + Node.js LTS
✅ PM2 多进程
✅ Nginx 反向代理
✅ 系统 ulimit 调优
✅ 内存参数明确
✅ NODE_ENV=production
如果你愿意,可以告诉我:
我可以给你 更精确的优化方案。