Nginx&uWSGI静态文件性能对比
前言

在实际部署Python Web应用时,我们往往会采用类似Nginx->uWSGI/Gunicorn->Python的三层架构。使用Nginx而不是直接使用uWSGI来处理HTTP请求的理由主要有以下几点:
- Nginx更安全;
- 需要实现负载均衡/URL转发;
- Nginx处理静态文件更快,缓存头更完善。
但在某些诸如简单Web应用、外部统一网关、单机单容器、内网环境等部署场景,Nginx的优势并不一定那么明显。本文着重分析Nginx、uWSGI的静态文件性能问题,辅助判断是否需要使用Nginx。
性能测试流程
- 创建测试文件
 生成大小为4k~512k的随机字符串文件作为测试样本
| 1 |  | 
- 启动测试容器 - 1 
 2- docker run -d -v $(pwd):/static --name pytest python:3.6-jessie tail -f /dev/null
 docker exec -it pytest bash
- 配置并启动Nginx和uWSGI - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15- apt update && apt install -y nginx apache2-utils
 pip install uwsgi
 cat >/etc/nginx/conf.d/default.conf<<EOF
 server {
 listen 81 default_server;
 location / {
 root /static;
 }
 }
 EOF
 # 启动nginx和uWSGI
 service nginx start
 uwsgi --master --http 0.0.0.0:82 --static-map /=/static
- 开始测试 
 使用- Apache Benchmark对Nginx和uWSGI的静态文件进行测试,并发数为100,共请求20000次。提取测试结果中的关键参数:- Requests per second。- 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10- cd /static
 for fn in *.hex; do
 echo -e "\n$fn"
 echo "nginx (keep alive)"
 ab -q -k -c 100 -n 20000 127.0.0.1:81/$fn | grep -Po 'Requests per second:[ \d]+'
 echo "nginx"
 ab -q -c 100 -n 20000 127.0.0.1:81/$fn | grep -Po 'Requests per second:[ \d]+'
 echo "uwsgi"
 ab -q -c 100 -n 20000 127.0.0.1:82/$fn | grep -Po 'Requests per second:[ \d]+'
 done
测试结果

其中nginx (keep-alive)项为理论最好情况,实际应用中很难达到。uWSGI在处理静态文件时不支持keep-alive模式。
假设将未使用keep-alive的Nginx性能作为基准,可得出下表:
| 文件大小 | nginx(keep-alive) | nginx | uwsgi | 
|---|---|---|---|
| 4k | 157% | 100% | 43% | 
| 8k | 204% | 100% | 42% | 
| 16k | 202% | 100% | 34% | 
| 32k | 207% | 100% | 26% | 
| 64k | 173% | 100% | 20% | 
| 128k | 160% | 100% | 14% | 
| 256k | 151% | 100% | 11% | 
| 512k | 125% | 100% | 10% | 
由此可以看出,uWSGI在处理小体积静态文件上的效率能达到Nginx的三、四成,但当静态文件体积增加到64k及以上时,其效率就远比不上Nginx了。
Nginx&uWSGI静态文件性能对比
      https://www.yooo.ltd/2019/02/20/Nginx-uWSGI静态文件性能对比/