使用 Gunicorn 對 Django 應用程式發出 100 個並發請求會導致「54:連線由對等方重置」和 502

使用 Gunicorn 對 Django 應用程式發出 100 個並發請求會導致「54:連線由對等方重置」和 502

我正在託管一個充當 API 端點的 Django 應用程式。不幸的是,使用該 API 的應用程式在頁面載入時會執行大量並發請求(在 80-90 個請求範圍內)。

Nginx 作為gunicorn 前面的反向代理運行並報告以下問題: kevent() reported that connect() failed (54: Connection reset by peer) while connecting to upstream

這讓我開始嘗試縮放gunicorn。我嘗試-k gevent並增加了--worker-connections,但沒有多大幫助。我在--threads和 同步工作者方面也取得了同樣的成功。

Listen queue overflow: 16 already in queue awaiting acceptance (55 occurrences)我注意到in出現了幾次dmesg,這導致我增加到kern.ipc.somaxconn4096,但同樣:沒有成功。

根據gunicorn文檔,我用來hey查看代理是否正在做正確的事情並對端點進行負載測試: hey -c 100 -n 200 -H "Authorization: token ${token}" 'https://example.com/api/'

它會返回一些類似的內容(有時更好一點,有時更差一點):

Status code distribution:
  [200] 126 responses
  [502] 74 responses

相關 nginx 設定:

worker_processes  auto;

events {
    worker_connections  1024;
    accept_mutex on;
    use kqueue;
}

upstream backend-api {
  server 127.0.0.1:8000 fail_timeout=0;
}

server {
    listen 443 ssl http2 accept_filter=httpready;
    server_name example.com;

    ssl_certificate /usr/local/etc/nginx/sites/example.com.crt;
    ssl_certificate_key /usr/local/etc/nginx/sites/example.com.key;

    location = /favicon.ico { access_log off; log_not_found off; }
    root /usr/local/www/example.com/web;
    index index.html ;

    keepalive_timeout 5;

    location ~  ^/(static|assets|index.html|$) {
        root /usr/local/www/example.com/web;
    }

    location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Forwarded-Host $http_host;
      proxy_set_header X-Real-IP $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;
      proxy_intercept_errors on;
      proxy_pass http://backend-api;
    }
}

運行gunicorn: gunicorn --workers=9 --bind 0.0.0.0:8000 --forwarded-allow-ips='*' -k gevent --worker-connections=1000 api.wsgi'

我似乎無法找到解決方案。無論我嘗試什麼,我只能在頁面加載時獲得“更少”的 502,但從來沒有可靠地獲得過。我缺什麼?

Gunicorn 沒有報告任何問題 - 請求似乎從未達到那麼遠。

相關內容