在CentOS上优化Node.js的网络连接,可以从多个方面入手,包括系统配置、Node.js应用配置、网络参数调整等。以下是一些常见的优化方法:
Node.js应用通常需要处理大量的并发连接,因此需要增加系统的文件描述符限制。
# 查看当前限制 ulimit -n # 临时增加限制 ulimit -n 65535 # 永久增加限制(编辑 /etc/security/limits.conf) * soft nofile 65535 * hard nofile 65535 编辑 /etc/sysctl.conf 文件,增加以下参数:
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 然后运行 sysctl -p 使配置生效。
HTTP/2 提供了多路复用、头部压缩等特性,可以显著提高性能。
const http2 = require('http2'); const fs = require('fs'); const server = http2.createSecureServer({ key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt') }); server.on('stream', (stream, headers) => { stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('<h1>Hello World</h1>'); }); server.listen(8443); Node.js 的集群模块可以利用多核CPU,提高应用的并发处理能力。
const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { console.log(`Master ${process.pid} is running`); // Fork workers. for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); }); } else { // Workers can share any TCP connection // In this case it is an HTTP server http.createServer((req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000); console.log(`Worker ${process.pid} started`); } 编辑 /etc/sysctl.conf 文件,增加以下参数:
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 使配置生效。
编辑 /etc/sysctl.conf 文件,增加以下参数:
net.ipv4.tcp_fastopen = 3 然后运行 sysctl -p 使配置生效。
使用Nginx或Apache作为反向代理,可以进一步提高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; } } 通过以上方法,可以显著优化CentOS上Node.js的网络连接性能。根据具体应用场景和需求,可以选择合适的优化策略。