相关参数配置
查看Backlog限制数
shell> ss -ln
Recv-Q Send-Q Local Address:Port Peer Address:Port
0 511 *:80 *:*
0 128 127.0.0.1:9000 *:*
Send-Q:nginx默认值511,PHP-FPM默认值128
扩展命令:
# 仅查看php相关进程
ss -ln |grep -E 'php|Netid'
/etc/sysctl.conf配置文件
# 定义了系统中每一个端口最大的监听队列的长度,这是个全局的参数。backlog需要设置这个
net.core.somaxconn = 20480
# 对于还未获得对方确认的连接请求,可保存在队列中的最大数目。如果服务器经常出现过载,可以尝试增加这个数字。
net.ipv4.tcp_max_syn_backlog = 20480
# 在每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。
net.core.netdev_max_backlog = 20480
配置方式
- 方法一(重启无效)
# 查看当前值
sysctl -a | grep net.core.somaxconn
# 临时设置
echo 20480 > /proc/sys/net/core/somaxconn
or
sysctl -w net.core.somaxconn=20480
- 方法二(永久)
vi /etc/sysctl.conf
# 添加
net.core.somaxconn = 20480
net.core.netdev_max_backlog = 20480
net.ipv4.tcp_max_syn_backlog = 20480
net.ipv4.tcp_max_tw_buckets = 800000
# 然后在终端中执行,使之生效
sysctl -p
# 亲测需要重启才生效
reboot
nginx配置文件
-
worker_processes
:设置与cpu核数一致或高版本nginx设置auto -
worker_connections
:单个⼯作进程可以允许同时建⽴外部连接的数量数字越⼤,能同时处理的连接越多
1.connections不是随便设置的,⽽是与两个指标有重要关联,⼀是内存,⼆是操作系统级别的“进程最⼤可打开⽂件数”。
2.内存:每个连接数分别对应⼀个read_event、⼀个write_event事件,⼀个连接数⼤概占⽤232字节,2个事件总占⽤96字节,那么
⼀个连接总共占⽤328字节,通过数学公式可以算出100000个连接数⼤概会占⽤ 31M = 100000 * 328 / 1024 / 1024,当然这
只是nginx启动时,connections连接数所占⽤的nginx。
3.进程最⼤可打开⽂件数:进程最⼤可打开⽂件数受限于操作系统,可通过 ulimit -n 命令查询,以前是1024,现在是65535,
nginx提供了worker_rlimit_nofile指令,这是除了ulimit的⼀种设置可⽤的描述符的⽅式。 该指令与使⽤ulimit对⽤户的设置是同样的效果。此指令的值将覆盖ulimit的值,如:worker_rlimit_nofile 20960;
设置ulimits:ulimit -SHn 65535
通过 ps -elf | grep nginx 找到 nginx 的worker进程ID
通过 cat /proc/31613/limits 查看,其中2291是worker进程ID,请注意其中的Max open files
- backlog值调高
server {
listen 80 backlog=20480;
listen 443 ssl backlog=20480;
...
}
修改后重启Nginx生效
PHP配置
修改php-fpm.conf
# 默认值为-1,说是随系统配置,其实还是只有128
listen.backlog = 8129
修改后重启PHP生效
参考资料:
https://blog.csdn.net/beyondlpf/article/details/52871932
https://blog.csdn.net/Dream_Flying_BJ/article/details/60964939
https://blog.csdn.net/weixin_30205357/article/details/115779348
http://t.zoukankan.com/itcomputer-p-10642036.html
https://blog.huoding.com/2014/08/13/367
https://www.04007.cn/article/323.html
长连接框架使用Nginx转发时需要的优化
场景
错误提示:socket() failed (24: Too many open files) while connecting to upstream
错误描述:偶尔出现nignx500错误,但刷新后则显示正常。观察ningx的错误日志,发现很多的如下的错误:
2021/05/10 09:26:03 [alert] 30940#0: *1217975628 socket() failed (24: Too many open files) while connecting to upstream, client: x.x.x.x, server: localhost, request: "GET / HTTP/1.1", upstream: "http://x.x.x.x:80", host: "x.x.x.x"
查看max open files
查看nginx.pid的路径:
find / -name nginx.pid
查看nginx的 max open files:
grep 'open files' /proc/$( cat /usr/local/nginx/logs/nginx.pid )/limits
解决
修改linux打开文件句柄数,编辑vi /etc/security/limits.conf
,添加
<domain> <type> <item> <value>
* soft nofile 204800
* hard nofile 204800
星号代表全局, soft为软件,hard为硬件,nofile为这里指可打开文件数。
修改nginx打开文件数, 编辑nginx.conf,添加worker_rlimit_nofile值
worker_processes 1;
worker_rlimit_nofile 65535;
events {
worker_connections 65535;
}
重启nginx后问题解决。
参考资料
http://www.884358.com/nginx-too-many-open-files/