ab(Apache Benchmark)是一个简单易用的HTTP服务器性能测试工具,可以用来对Nginx服务器进行压力测试。以下是配置和使用ab进行Nginx压力测试的详细指南。
在大多数Linux发行版中,ab是Apache工具包的一部分:
# Debian/Ubuntu
sudo apt-get install apache2-utils
# CentOS/RHEL
sudo yum install httpd-tools
最基本的ab测试命令格式:
ab -n 1000 -c 100 http://your-nginx-server.com/
-n 1000
: 总请求数-c 100
: 并发请求数-n requests
: 执行请求的总数-c concurrency
: 并发请求数-t timelimit
: 测试持续的最长时间(秒)-s timeout
: 请求超时时间(秒),默认30秒-k
: 启用HTTP KeepAlive功能-H "header: value"
: 添加自定义请求头-A auth-username:password
: 基本认证-T content-type
: POST/PUT时的内容类型-p POST-file
: 包含POST数据的文件-u PUT-file
: 包含PUT数据的文件-v verbosity
: 详细级别(1-4)ab -n 5000 -c 200 http://localhost/
ab -n 5000 -c 200 -k http://localhost/
ab -n 1000 -c 50 -p postdata.txt -T 'application/x-www-form-urlencoded' http://localhost/api
ab -n 1000 -c 100 -A username:password http://localhost/secure/
ab测试完成后会输出类似以下结果:
Server Software: nginx/1.18.0
Server Hostname: localhost
Server Port: 80
Document Path: /
Document Length: 612 bytes
Concurrency Level: 100
Time taken for tests: 1.234 seconds
Complete requests: 1000
Failed requests: 0
Total transferred: 850000 bytes
HTML transferred: 612000 bytes
Requests per second: 810.37 [#/sec] (mean)
Time per request: 123.400 [ms] (mean)
Time per request: 1.234 [ms] (mean, across all concurrent requests)
Transfer rate: 672.76 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 1 0.5 1 5
Processing: 10 120 20.1 115 210
Waiting: 10 120 20.1 115 210
Total: 10 121 20.1 116 211
Percentage of the requests served within a certain time (ms)
50% 116
66% 125
75% 130
80% 135
90% 150
95% 165
98% 180
99% 190
100% 211 (longest request)
重点关注指标: - Requests per second: 每秒处理的请求数(QPS),越高越好 - Time per request: 每个请求的平均处理时间,越低越好 - Failed requests: 失败请求数,应为0 - Percentage served within time: 请求响应时间分布
nginx
worker_processes auto; # 通常设置为CPU核心数
events {
worker_connections 1024; # 每个worker的最大连接数
}
ulimit -n
)ab本身不支持多URL测试,但可以通过脚本实现:
for url in page1 page2 page3; do
ab -n 1000 -c 100 "http://localhost/$url" > "result_$url.txt" &
done
wait
ab -n 100000 -c 500 -t 60 http://localhost/
ab -n 1000 -c 100 -C "sessionid=1234" http://localhost/
ab -n 1000 -c 100 -e result.csv http://localhost/
通过合理配置ab工具和正确解读测试结果,您可以全面评估Nginx服务器的性能表现,找出性能瓶颈并进行优化。