Ubuntu下Node.js应用性能调优指南
Node.js处理高并发时需大量文件描述符,需修改系统限制以避免“Too many open files”错误。
ulimit -n 65535(仅当前会话有效)。/etc/security/limits.conf,添加以下内容:* soft nofile 65535
* hard nofile 65535
/etc/pam.d/common-session和/etc/pam.d/common-session-noninteractive,添加:session required pam_limits.so
重启系统或重新登录使配置生效。调整TCP/IP栈参数提升网络性能,编辑/etc/sysctl.conf:
net.core.somaxconn = 4096 # 监听队列最大长度
net.ipv4.tcp_max_syn_backlog = 4096 # SYN队列长度
net.ipv4.ip_local_port_range = 1024 65535 # 可用端口范围
net.ipv4.tcp_tw_reuse = 1 # 复用TIME-WAIT连接
net.ipv4.tcp_fin_timeout = 30 # TIME-WAIT超时时间(秒)
执行sudo sysctl -p使配置生效。
SSD的随机读写性能远优于传统HDD,能显著提升文件IO密集型应用(如数据库、日志处理)的性能。建议将Ubuntu系统和Node.js应用部署在NVMe SSD上。
新版本通常包含性能改进和bug修复。使用nvm(Node Version Manager)管理版本:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
nvm install --lts
nvm use --lts
避免使用过时版本(如Node.js 14及以下)。
fs.promises.readFile()替代fs.readFileSync(),用async/await处理异步逻辑,避免阻塞事件循环。var变量),及时移除无用的事件监听器(emitter.off()),使用WeakMap/WeakSet管理缓存。stream模块(如fs.createReadStream())替代一次性读取,减少内存占用。利用多核CPU提升并发能力。示例如下:
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
const numCPUs = os.cpus().length;
console.log(`Master ${process.pid} is running with ${numCPUs} CPUs`);
for (let i = 0; i < numCPUs; i++) cluster.fork(); // 创建工作进程
cluster.on('exit', (worker) => console.log(`Worker ${worker.process.pid} died`));
} else {
require('./app.js'); // 工作进程启动应用
}
或使用PM2的-i max参数自动启动集群(见下文)。
通过命令行参数调整V8内存限制:
node --max-old-space-size=4096 app.js # 设置堆内存上限为4GB(默认1.4GB)
适用于内存密集型应用(如大数据处理)。
PM2提供进程守护、负载均衡、日志管理、性能监控等功能。安装与使用:
sudo npm install pm2 -g
pm2 start app.js --name "my-app" -i max # 启动集群(-i max表示按CPU核心数启动)
pm2 monit # 实时监控CPU、内存
pm2 logs # 查看日志
pm2 save # 保存当前进程列表
pm2 startup # 设置开机自启
PM2的集群模式会自动调用cluster模块,简化部署。
使用Nginx作为反向代理,处理静态文件、负载均衡和SSL卸载,减轻Node.js负担。示例Nginx配置:
server {
listen 80;
server_name example.com;
location /static/ {
alias /var/www/static/; # 静态文件由Nginx直接处理
expires 30d;
}
location / {
proxy_pass http://localhost:3000; # 转发到Node.js应用
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;
}
}
重启Nginx:sudo systemctl restart nginx。
const { performance, PerformanceObserver } = require('perf_hooks');
const obs = new PerformanceObserver((items) => {
console.log(items.getEntries()[0].duration); // 打印耗时
performance.clearMarks();
});
obs.observe({ entryTypes: ['measure'] });
performance.mark('A');
// 需要监控的代码
performance.mark('B');
performance.measure('A to B', 'A', 'B');
setInterval(() => {
console.log('Memory:', process.memoryUsage());
console.log('CPU:', process.cpuUsage());
}, 5000);
pm2 monit查看实时CPU、内存;pm2 plus提供云端监控。pg-pool for PostgreSQL),批量操作替代多次查询。spdy模块启用HTTP/2,提升多路复用性能。splitChunks分割代码,后端路由懒加载(如express.Router())。