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限流

相关推荐
维尔切1 分钟前
Linux中基于Centos7使用lamp架构搭建个人论坛(wordpress)
linux·运维·架构
丘大梨1 小时前
QT 基础聊天应用项目文档
运维·数据库·系统架构
怀刃2 小时前
C# 内存监控怎么定位问题
运维
TPBoreas2 小时前
Jenkins启动端口修改失败查找日志
运维·服务器·jenkins
正在努力的小河4 小时前
Linux设备树简介
linux·运维·服务器
荣光波比4 小时前
Linux(十一)——LVM磁盘配额整理
linux·运维·云计算
小晶晶京京4 小时前
day35-负载均衡
运维·网络·网络协议·学习·负载均衡
拾心215 小时前
【运维进阶】LNMP + WordPress 自动化部署实验
运维·自动化·ansible·mariadb
大路谈数字化6 小时前
Centos中内存CPU硬盘的查询
linux·运维·centos
赏点剩饭7788 小时前
linux中的hostpath卷、nfs卷以及静态持久卷的区别
linux·运维·服务器