在linux中,一切皆文件,所以连接数本身也会表现为文件打开数。默认情况下,linux单进程打开文件数的限制是1024 , 非常低,在密集io型服务里很容易超过。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# vi /etc/sysctl.conf ,末尾添加
fs.file-max = 655350000sss
fs.nr_open = 655350000

# 执行命令生效
sysctl -p
# 查看 max-file:
cat /proc/sys/fs/file-max
# 查看当前系统总打开文件数
cat /proc/sys/fs/file-nr
# 输出: 9344 0 592026,
# 分别为:1.已经分配的文件句柄数,2.已经分配但没有使用的文件句柄数,3.最大文件句柄数。
# 修改系统对单个进程打开的文件数限制
ulimit -n 655350000
echo "* soft nofile 655350000" >> /etc/security/limits.conf
echo "* hard nofile 655350000" >> /etc/security/limits.conf
# 顺便附上查看各个进程打开的文件数的命令。显示格式是文件数 + 进程id
lsof -n |awk '{print $2}'|sort|uniq -c|sort -nr|more

# 如果有安装nginx做转发,则还需要设置nginx
#打开nginx本身的文件数限制
vi /etc/nginx/nginx.conf
# 找到相应位置覆盖修改这个配置
worker_rlimit_nofile 655350000;
events {
worker_connections 65535;
}

vi /etc/sysctl.conf 末尾添加tcp连接数相关配置
net.core.somaxconn = 20480
net.core.rmem_default = 262144
net.core.wmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 4096 16777216
net.ipv4.tcp_wmem = 4096 4096 16777216
net.ipv4.tcp_mem = 786432 2097152 3145728
net.ipv4.tcp_max_syn_backlog = 16384
net.core.netdev_max_backlog = 20000
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_max_orphans = 131072
net.ipv4.tcp_syncookies = 0
之后执行 sysctl -p 生效