解决 django 应用程序中 CPU 使用率过高的问题

Des*_*esh 5 django nginx cpu-usage gunicorn docker

我尝试优化我的 django Web 应用程序以增加最大 rps。我的堆栈包括 docker+django+gunicorn+nginx

我用 yandex.tank 做了性能测试。

当 rps 负载大约为 15 时,请求开始失败。

坦克写道: "110 Connection timed out"

在 nginx access.log 我有:

 "xxx.xxx.xxx.xxx - - [27/Aug/2019:17:37:52 +0000] "GET /url HTTP/1.1" 499 0 "-" "Tank" 5.257 - [5.256]"
Run Code Online (Sandbox Code Playgroud)

当我在此测试期间打开 htop 时,我看到所有服务器核心都以 100% 加载

我曾尝试使用 proxy_read_timeout、keepalive 设置但没有结果。


upstream app {
    server django:5000;
 }

server {
    listen 80;
    server_name my.site.com;

    listen 443 ssl;

    ssl_certificate /etc/letsencrypt/live/my.site.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/my.site.com/privkey.pem;

    client_max_body_size 4G;

    access_log /var/log/nginx/access.log combined_plus;
    error_log /var/log/nginx/error.log;

    gzip             on;
    gzip_comp_level  2;
    gzip_min_length  1000;
    gzip_proxied     expired no-cache no-store private auth;
    gzip_types       text/plain application/x-javascript text/xml text/css application/xml;

    location / {
        proxy_pass http://django:5000;
        proxy_redirect off;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 300;
    }

    location /static {
        alias /app/static/;
    }

    location /media {
        alias /app/media/;
    }
}

Run Code Online (Sandbox Code Playgroud)

配置文件


user  nginx;
worker_processes  8;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format combined_plus '$remote_addr - $remote_user [$time_local]'
                         ' "$request" $status $body_bytes_sent "$http_referer"'
                         ' "$http_user_agent" $request_time $upstream_cache_status'
                         ' [$upstream_response_time]';

    access_log  /var/log/nginx/access.log  combined_plus;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
Run Code Online (Sandbox Code Playgroud)

gunicorn 运行命令

 "xxx.xxx.xxx.xxx - - [27/Aug/2019:17:37:52 +0000] "GET /url HTTP/1.1" 499 0 "-" "Tank" 5.257 - [5.256]"
Run Code Online (Sandbox Code Playgroud)

我无法理解问题是由于 nginx 和 gunicorn 配置错误或在 django 应用程序代码中引起的。

我如何测试这个或配置我的应用程序以了解为什么 gunicorn 工作人员加载 CPU 如此之多?

我的机器上有 10 个内核和 64 个内存。

更新: 负载下的 htop 调用显示有很多 postgres“事务空闲”进程。