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

相关推荐
知远同学2 小时前
docker学习笔记2-最佳实践
运维·docker·容器
哈哈幸运4 小时前
MySQL运维三部曲初级篇:从零开始打造稳定高效的数据库环境
linux·运维·数据库·mysql·性能优化
黑心老人4 小时前
Mac OS系统下kernel_task占用大量CPU资源导致系统卡顿
linux·运维·服务器·macos
光算科技4 小时前
服务器在国外国内用户访问慢会影响谷歌排名吗?
运维·服务器·c++
口嗨农民工4 小时前
ubuntu18.04启动不了修复
linux·运维·ubuntu
YUELEI1184 小时前
Centos9 安装 nginx 及配置
nginx·centos
塔能物联运维5 小时前
双轮驱动能源革命:能源互联网与分布式能源赋能工厂能效跃迁
大数据·运维
GalaxyPokemon6 小时前
Muduo网络库实现 [十六] - HttpServer模块
linux·运维·服务器·网络
461K.6 小时前
spark与hadoop的区别
大数据·运维·hadoop·分布式·spark·intellij-idea
Zfox_6 小时前
Git 进阶之路:高效协作之分支管理
大数据·linux·运维·c++·git·elasticsearch