如何使用 gunicorn 部署 Django + Whitenoise 应用程序?

How to deploy a Django + Whitenoise application using gunicorn?

我正在使用 Whitenoise to serve static files in my Django app. I am NOT using Nginx. I plan to use Whitenoise behind a CDN like Cloudfront in the future. See Whitenoise FAQs

我一直在寻找解决这些问题的部署说明:

  1. 由于我没有使用nginx,所以打算直接绑定gunicorn到80端口,这样就报错-Permission Denied。我可以 运行 gunicorn 作为 root,但这似乎是一个糟糕的方法。

  2. 如何处理 SSL 证书的东西?通常这是由像 Nginx 这样的服务器处理的。

编辑:我正在Ubuntu 18.04 VM Google Cloud Compute Engine 上部署我的应用程序。

P.S.: 我的网站不会成为一个流量很高的网站。其他人使用此配置为高流量网站提供服务。看到这个 Squeezing every drop of performance out of a Django app on Heroku.

TL;DR

我使用nginx 作为http 服务器。我去掉了nginx中与静态文件相关的配置,这样静态文件请求就被传递给了wsgi层(gunicorn),由Whitenoise来处理。因此,您可以关注任何 'nginx + gunicorn + django' 部署 instructions/tutorials,这些部署很容易通过简单的 google 搜索获得。

这个 post 帮我搞定了:Deploying your Django static files to AWS (Part 2)

长答案

如前所述,有很多关于在 Heroku 上部署 Django + Whitenoise 应用程序的教程。正如评论中指出的那样:

Heroku, which has its own proxy layer in the front end, and is therefore not at all relevant.

未经验证,我认为这一定是真的。 gunicorn 不是一个完整的网络服务器。事实上,gunicorn 的创建者强烈建议在代理服务器(例如 Nginx)后面使用它。 See docs

我很困惑,因为我一直认为 Nginx 只是一个反向代理。作为静态资产的反向代理功能只是nginx的功能之一。它提供了更多功能,例如缓冲慢速客户端(gunicorn 没有),这有助于防止 denial-of-service 攻击。

我早就知道了。不使用 nginx 或任何其他网络服务器是愚蠢的。

Whitenoise 可以为静态文件设置适当的缓存 headers 并使用 gzip/brotli 启用压缩。与whitenoise.storage.CompressedManifestStaticFilesStorage一起使用时,会自动生成版本化的静态文件。例如。 /static/js/app.49ec9402.js 如果您已将文件作为 {%statis%} 'js/app.js' 放入模板中。版本化文件将 max-age 设置为 10 年,即永远缓存。

如果您不在 Heroku 上部署,您仍然需要像 Nginx 这样的 Web 服务器。因此,您可以关注任何 'nginx + gunicorn + django' 部署 instructions/tutorials,通过简单的 google 搜索即可轻松获得。其中之一是 Deploying your Django static files to AWS (Part 2),它帮助我解决了这个问题。