Django + Nginx + Gunicorn - 为什么我的 TTFB 这么高?

Django + Nginx + Gunicorn - Why is my TTFB so high?

这是我第一次使用 nginx/gunicorn 设置 Web 服务器,所以如果有任何明显的原因可以说明为什么我的 TTFB 如此之高,我深表歉意。

根据 gtmetrix.com 我的 TTFB 是 1.4s:

在我自己的测试中,我的 TTFB 约为 1.3 秒。

我很困惑为什么它这么高,即使我启用了 Brotli、缓存(静态和媒体文件)、Http2,我启用了 html 缩小器,所以我不知道为什么。我的服务器是纽约 Digital Ocean 的 2GB CPU(靠近我所在的地方),所以位置不是问题。我检查了 this 堆栈溢出问题,但删除 django-htmlmin 包仍然有很高的 ttfb。我在这个页面上的 django 视图只是:

@minified_response
def home(request):
    context = {
        'posts': Post.objects.all()
    }
    return render(request, 'blog/home.html', context)

我认为这是一个简单的查询,我不希望 TTFB 仅仅为了这个 get 查询就这么高。我的数据库有问题吗(现在我正在使用sqlite)?如果您需要我的任何其他文件或东西来帮助我调试,请告诉我。

此外,根据 Cloudflare 的 this 文章,我的 TTFB 很高,因为

At CloudFlare we make extensive use of nginx and while investigating TTFB came across a significant difference in TTFB from nginx when compression is or is not used. Gzip compression of web pages greatly reduces the time it takes a web page to download, but the compression itself has a cost. That cost causes TTFB to be greater even though the complete download is quicker.

所以我尝试删除 Brotli,但 TTFB 仍然相当高,在 Nginx conf 文件中禁用 gzip 对 TTFB 没有帮助。

描述: Nginx-Gunicorn 服务器使用 Digitalocean NYC 2GB CPU 在 Django(sqlite 数据库)上

编辑: 我停止使用 Cloudflare,因为我遇到了一些问题。

检查了这个:https://www.digitalocean.com/community/questions/how-can-i-improve-the-ttfb

事实证明,使用 fastcgi 缓存可以大大加快速度。我之前的 ttfb 大约是 1300ms,现在(如果没有来自服务器的更新)ttfb 大约是 10~40ms,但是如果页面是从服务器的数据更新的,ttfb 大约是 1300~2000ms,但是我没关系。如果使用 fastcgi_cache 有任何问题请告诉我,但到目前为止没有任何问题。我的 Nginx 文件:

# Other Stuff
fastcgi_cache_path /etc/nginx-cache levels=1:2 keys_zone=djangocache:100m inactive=60m;
fastcgi_cache_key # Your Cache Key (Ex: https://example.com/);
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
# ...
server {
    # more stuff
    location / {
          fastcgi_cache_valid 301 30d;
          fastcgi_cache djangocache;
          fastcgi_cache_valid 200 30m;
          fastcgi_cache_methods GET HEAD;
          fastcgi_cache_use_stale updating;
          fastcgi_cache_background_update on;
          fastcgi_pass # Your server name;
          fastcgi_param PATH_INFO $fastcgi_script_name;
          fastcgi_param REQUEST_METHOD $request_method;
          fastcgi_param CONTENT_TYPE $content_type;
          fastcgi_param CONTENT_LENGTH $content_length;
          add_header X-Fastcgi-Cache $upstream_cache_status;
          # ...
    }
    # ...
}

如果您发现我上面的代码有任何问题请告诉我,我仍在尝试使用 fastcgi 缓存。

编辑 2: 小心模板中 {% load %} 的模块,因为其中一些模块会大大降低 ttfb 的速度。我正在使用 profanity check,我将其从我的模板中删除,这将 ttfb 减少了大约 750 毫秒。 ttfb 的最大修复(至少在我的情况下)是检查第三方包以及您在模板中加载的内容。

编辑 3: 对我的 TTFB 有帮助的另一件大事是删除包 django-htmlmin。删除它使我的 TTFB 下降了 300 毫秒,所以现在我的 ttfb 是 10~40 毫秒(没有服务器更新)或 200~500 毫秒(服务器更新),我很满意。