CentOS 上 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 61999
net.ipv4.tcp_tw_reuse = 1
# 关闭 tcp_tw_recycle(在 NAT/负载均衡或多主机环境易出问题)
# net.ipv4.tcp_tw_recycle = 0 或删除该行
# 加速回收
net.ipv4.tcp_fin_timeout = 30
# 可选:启用 TCP Fast Open(需客户端也支持)
# net.ipv4.tcp_fastopen = 3
# 可选:启用 syncookies(抵御小规模 SYN Flood)
# net.ipv4.tcp_syncookies = 1
# 套接字/内核内存缓冲
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
执行 sysctl -p 使配置生效;按需开启可选参数。上述取值可显著提升并发连接与短连接处理能力。二 Node.js 应用层优化
三 架构与反向代理
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost: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;
}
location /static/ {
root /path/to/static/files;
}
}
四 监控与压测
curl -w "
DNS解析 : %{time_namelookup}s
TCP连接 : %{time_connect}s
服务器处理: %{time_starttransfer}s
总耗时 : %{time_total}s\n" -o /dev/null -s http://example.com
五 常见瓶颈与排查