nginx-限制客户端并发数

文章目录


前言

瞬时大量用户访问服务器,导致服务器超载而宕机。

恶意请求攻击服务器,导致服务器超载而宕机。

nginx如何限制每个客户端的并发连接数?


一、ngx_http_limit_conn_module

生效阶段: NGX_HTTP_PREACCESS_PHASE

模块默认编译进nginx,通过--without-http_limit_conn_module禁用。

生效范围:

  • 全部worker进程(基于共享内存)
  • 进入preaccess阶段前不生效
  • 限制的有效性取决于key的设计:依赖postread阶段的realip模块取到真实的IP。
    ngx_http_limit_conn_module官方传送门

二、指令介绍

1. limit_conn_zone

定义共享内存(包含大小),以及key关键字

代码如下(示例):

bash 复制代码
Syntax:	limit_conn_zone key zone=name:size;
Default:	---
Context:	http

2.limit_conn

限制并发连接数

代码如下(示例):

bash 复制代码
Syntax:	limit_conn zone number;
Default:	---
Context:	http, server, location

3. limit_conn_log_level

限制发生时的日志级别

bash 复制代码
Syntax:	limit_conn_log_level info | notice | warn | error;
Default:	
limit_conn_log_level error;
Context:	http, server, location
This directive appeared in version 0.8.18.

4. limit_conn_status

限制发生时向客户端返回的错误码

bash 复制代码
Syntax:	limit_conn_status code;
Default:	
limit_conn_status 503;
Context:	http, server, location
This directive appeared in version 1.3.15.

案例

未限制

现在limit_conn是注释状态

bash 复制代码
[root@test20 nginx]# cat conf.d/limit_conn.conf 
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
	server_name limit_conn.test.io;
        root html/;
	error_log  /var/log/nginx/myerror.log info;        
        location / {
		#limit_conn_status 500;
 		#limit_conn_log_level warn;
		#limit_conn addr 1;
	}
}
# 如上,定义了一个addr的共享区域,用$binary_remote_addr作为key。

# 用ab 压测
ab -c 1000 -n 100000 http://limit_conn.test.io/limit.html

# 查看access.log的内容,分析返回状态码,全部返回200
[root@test20 nginx]# cat /var/log/nginx/access.log | awk -F' ' '{print $9}' | sort | uniq -c
      1 
 100000 200

限制

bash 复制代码
[root@test20 nginx]# cat conf.d/limit_conn.conf 
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
	server_name limit_conn.test.io;
        root html/;
	error_log  /var/log/nginx/myerror.log info;        
        location / {
		limit_conn_status 500;
 		limit_conn_log_level warn;
		limit_conn addr 1;
	}
}
# 如上,定义了一个addr的共享区域,用$binary_remote_addr作为key。

# 用ab 压测
ab -c 1000 -n 100000 http://limit_conn.test.io/limit.html

# 查看access.log的内容,分析返回状态码,有部分返回了500
[root@test20 nginx]# cat /var/log/nginx/access.log | awk -F' ' '{print $9}' | sort | uniq -c
      1 
 170998 200
   2676 500

总结

下一节,介绍nginx限流

相关推荐
知白守黑2671 小时前
Ansible角色
运维·服务器·ansible
Jwest20211 小时前
工业显示器在地铁电力监控与运维中的应用
运维·计算机外设
fuyongliang1235 小时前
nginx反向代理,负载均衡,tomcat的数据流向图篇解析
nginx·tomcat·负载均衡
tuokuac6 小时前
nginx配置前端请求转发到指定的后端ip
前端·tcp/ip·nginx
Mr. Cao code7 小时前
Docker:颠覆传统虚拟化的轻量级革命
linux·运维·ubuntu·docker·容器
wanhengidc8 小时前
云手机运行流畅,秒开不卡顿
运维·网络·科技·游戏·智能手机
笨小孩@GF 知行合一9 小时前
OSPF实验:外部路由引入
运维·网络·hcip·数通·ospf
asdfg12589639 小时前
为什么要在出口路由器router配置NAT与默认路由
运维·网络·计算机网络
bug攻城狮9 小时前
Skopeo 工具介绍与 CentOS 7 安装指南
linux·运维·centos
宇宙第一小趴菜10 小时前
08 修改自己的Centos的软件源
linux·运维·centos