Node.js 在 CentOS 的性能优化方法
一 系统层优化
ulimit -nulimit -n 65535* 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
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_fastopen = 3
执行 sysctl -p 使配置生效。以上可显著改善高并发下的连接排队、端口耗尽与 TIME_WAIT 问题。二 Node.js 运行时与多核扩展
export NODE_OPTIONS="--max-old-space-size=1024" # 单位 MB
node app.js
[Service]
Environment="NODE_OPTIONS=--max-old-space-size=1024"
ExecStart=/usr/bin/node /path/to/app.js
执行 systemctl daemon-reload && systemctl restart your-apppm2 start app.js --max-memory-restart 1G
三 反向代理与网络架构
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
如需 HTTP/2,在 listen 指令启用 http2 并配置 TLS 证书。四 代码与数据层优化
五 监控、剖析与容量规划