在 Debian 上优化 Node.js,一般可以从系统层面、Node 运行时、应用代码、部署方式几个维度来做。下面按实用性整理一份优化清单。
Debian 自带源中的 Node 通常较旧,建议用 NodeSource:
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs
Node 高并发时容易遇到 EMFILE:
ulimit -n 65535
永久生效:
/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
sysctl -w net.core.somaxconn=65535
sysctl -w net.ipv4.tcp_tw_reuse=1
写入 /etc/sysctl.conf 持久化。
export NODE_ENV=production
默认约 2GB(老版本 1.7GB):
node --max-old-space-size=4096 app.js
利用多核 CPU:
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
os.cpus().forEach(() => cluster.fork());
} else {
require('./app');
}
或使用 PM2:
npm i -g pm2
pm2 start app.js -i max
fs.readFileSync)async/awaitconst compression = require('compression');
app.use(compression());
Nginx 负责:
示例:
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
}
node --prof app.js
node --prof-process isolate-*.log > result.txt
npm i -g clinic
clinic doctor -- node app.js
node --inspectnpm ci 代替 npm install.dockerignore / .npmignorenpm audit| 场景 | 建议 |
|---|---|
| API 服务 | Nginx + PM2 + Cluster |
| 实时通信 | 使用 worker_threads |
| CPU 密集 | 拆分微服务 / 使用 C++ Addon |
| 低内存 VPS | 限制 --max-old-space-size |
如果你能说明:
我可以给你更针对性的优化方案。