在Linux系统中,要支持更多连接数(尤其是高并发场景),需要调整多个内核参数。以下是关键的调优步骤:
1. 文件描述符限制
系统级限制
# 查看当前限制
cat /proc/sys/fs/file-max
# 临时设置(重启后失效)
echo 1000000 > /proc/sys/fs/file-max
# 永久设置 - 编辑 /etc/sysctl.conf
echo "fs.file-max = 1000000" >> /etc/sysctl.conf
用户级限制
编辑 /etc/security/limits.conf:
* soft nofile 65536
* hard nofile 65536
root soft nofile 65536
root hard nofile 65536
Shell会话限制
# 临时设置
ulimit -n 65536
# 永久生效 - 添加到 /etc/profile 或用户 ~/.bashrc
echo "ulimit -n 65536" >> /etc/profile
2. 网络相关参数
编辑 /etc/sysctl.conf:
# 增加端口范围
net.ipv4.ip_local_port_range = 1024 65535
# 减少TIME_WAIT状态的超时时间
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
# 重用TIME_WAIT连接
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
# 增加连接队列长度
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 5000
# 增加TCP连接跟踪表大小
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_max_tw_buckets = 200000
# 扩大TCP连接数限制
net.ipv4.tcp_max_orphans = 65535
net.ipv4.tcp_max_syn_backlog = 65535
# 增加内存缓冲区
net.core.rmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_default = 262144
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
3. 应用服务器配置
Nginx示例
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 65535;
use epoll;
multi_accept on;
}
Node.js示例
// 增加文件描述符限制
const fs = require('fs');
process.setrlimit('nofile', { soft: 65535, hard: 65535 });
4. 应用层优化
连接池配置
# Python数据库连接池示例
import pymysql
from dbutils.pooled_db import PooledDB
pool = PooledDB(
creator=pymysql,
maxconnections=1000,
mincached=10,
maxcached=100,
blocking=True
)
5. 监控和验证
检查参数是否生效
# 查看文件描述符使用情况
lsof | wc -l
cat /proc/sys/fs/file-nr
# 查看网络连接状态
netstat -an | grep ESTABLISHED | wc -l
ss -s
# 查看TCP连接统计
cat /proc/net/sockstat
性能监控
# 实时监控连接数
watch -n 1 'netstat -an | grep :80 | wc -l'
# 监控文件描述符使用
watch -n 1 'lsof | wc -l'
6. 完整配置脚本
#!/bin/bash
# 设置文件描述符限制
echo "fs.file-max = 1000000" >> /etc/sysctl.conf
# 网络参数优化
cat >> /etc/sysctl.conf << 'EOF'
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_max_tw_buckets = 200000
net.ipv4.tcp_max_orphans = 65535
net.core.rmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_default = 262144
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
EOF
# 用户限制
cat >> /etc/security/limits.conf << 'EOF'
* soft nofile 65535
* hard nofile 65535
root soft nofile 65535
root hard nofile 65535
EOF
# 应用配置
echo "ulimit -n 65535" >> /etc/profile
# 重新加载配置
sysctl -p
注意事项
- 逐步调整:不要一次性设置过大值,逐步测试
- 内存考虑:每个连接占用内存,确保系统有足够RAM
- 应用支持:确保应用程序能处理大量连接
- 监控性能:调整后密切监控系统性能
- 备份配置:修改前备份原始配置文件
通过这些调整,Linux系统可以支持数十万甚至上百万的并发连接。
云小栈