在https上运行gunicorn?

dmy*_*ung 36 ssl https gunicorn

我们有一些Django设置通过代理(Apache和Nginx),最终进入实际的Django运行时.

我们需要在我们的网络中进行端到端的HTTPS.我们一直在重新审视Gunicorn,因为它在我们的其他设置中取得了成功和性能,但需要使用端到端的HTTPS进行测试才能保持一致.

我们的拓扑结构如下:

https://foo.com - > [面向公众的代理] - >(https) - > [内部服务器https:// 192 ...:8001]

如何配置Gunicorn使用自签名证书监听HTTPS?

Gre*_*egM 69

Gunicorn现在支持SSL,从版本17.0开始.您可以将其配置为侦听https,如下所示:

$ gunicorn --certfile=server.crt --keyfile=server.key test:app
Run Code Online (Sandbox Code Playgroud)

如果您使用--bind侦听端口80,请记住将端口更改为443(HTTPS连接的默认端口).例如:

$ gunicorn --certfile=server.crt --keyfile=server.key --bind 0.0.0.0:443 test:app
Run Code Online (Sandbox Code Playgroud)

  • @DrewV 如果您在 heroku 上部署,则无需自己支持 SSL - heroku 会为您完成。请参阅 [他们的文档](https://devcenter.heroku.com/articles/ssl-endpoint) 寻求帮助。您需要配置 gunicorn 以遵守 heroku 的安全标头配置。我在我的配置文件中使用了类似的东西:`forwarded_allow_ips = '*'` 和 `secure_scheme_headers = {'X-FORWARDED-PROTO': 'https',}` (3认同)

maf*_*sis 17

大量迟到的回复,但对于遇到此问题的其他人,还有另一个选项,使用nginx作为上面的"[面向公众的代理]".

配置nginx以处理端口443上的传入SSL流量,然后将proxy_pass配置为内部端口上的gunicorn.外部流量已加密,无论如何都不会暴露nginx和gunicorn之间的流量.我发现这很容易管理.

  • 因为你将gunicorn绑定到127.0.0.1,所以只有localhost可以访问它 (7认同)
  • 这样做的缺点是它破坏了 Django 的 `build_absolute_uri()` 函数;Django 将查看 HTTP 协议并使用该方案构建 URI,即使原始请求使用 HTTPS。 (6认同)
  • @robbrit,您可以设置标头来避免该问题。请参阅 [SECURE_PROXY_SSL_HEADER](https://docs.djangoproject.com/en/3.2/ref/settings/#secure-proxy-ssl-header) 文档。 (3认同)

gre*_*ou1 9

如果您使用gunicorn.config.py或类似的gunicorn配置文件,您可以添加证书文件和密钥文件。

certfile = '/etc/letsencrypt/live/example.com/fullchain.pem'
keyfile = '/etc/letsencrypt/live/example.com/privkey.pem'
Run Code Online (Sandbox Code Playgroud)

配置文件可用于将设置初始化为环境变量,如果您有大量设置,它会很有帮助。使用配置文件

  • 通过创建名为的文件来创建配置文件 gunicorn.config.py

  • 一些常用的设置是

      bind = "0.0.0.0:8000"
      workers = 4
      pidfile = 'pidfile'
      errorlog = 'errorlog'
      loglevel = 'info'
      accesslog = 'accesslog'
      access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
    
    Run Code Online (Sandbox Code Playgroud)

    而且当然

      certfile = '/etc/letsencrypt/live/example.com/fullchain.pem'
      keyfile = '/etc/letsencrypt/live/example.com/privkey.pem'
    
    Run Code Online (Sandbox Code Playgroud)

查看文档和配置文件示例

使用这些设置运行gunicorn

    $ gunicorn app:app
Run Code Online (Sandbox Code Playgroud)

自从

默认情况下,将从运行gunicorn 的同一目录中读取名为gunicorn.conf.py 的文件。


Gau*_*gla 5

除了certfileand之外,您还keyfile需要添加。ca-certs没有通过ca-certs,我就进入Trust anchor for certification path not found.了Android设备。

命令示例:

/usr/bin/python3 /usr/local/bin/gunicorn --bind 0.0.0.0:443 wsgi:app --workers=8 --access-logfile=/root/app/logs/access.log --error-logfile=/root/app/logs/error.log --certfile=/root/app/certificate.crt --keyfile=/root/app/private.key --ca-certs=/root/app/ca_bundle.crt --daemon
Run Code Online (Sandbox Code Playgroud)