在 Debian 上优化 Node.js 性能
一 系统层优化
* soft nofile 65535
* hard nofile 65535
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
二 运行时与多核扩展
sudo npm i -g pm2
pm2 start app.js -i max
或使用 Cluster 模块自行 fork 工作进程,分摊 CPU 与请求处理。node --max-old-space-size=4096 app.js
# 或在环境变量中
export NODE_OPTIONS="--max_old_space_size=4096"
三 代码与数据层优化
四 内存与 GC 调优
五 部署与运维实践
sudo apt-get install -y cgroup-tools
sudo cgcreate -g memory,cpu:/nodejs
sudo cgset -r memory.limit_in_bytes=268435456 nodejs # 256MB
sudo cgset -r cpu.shares=512 nodejs
sudo cgclassify -g memory,cpu:nodejs <PID>