我们有一些通过代理(Apache 和 Nginx)的 Django 设置,最终进入实际的 Django 运行时。
即使在我们的网络中,我们也需要端到端的 HTTPS。由于 Gunicorn 在我们其他设置中的成功和性能,我们一直在重新审视它,但需要使用 HTTPS 进行端到端测试以保持一致。
我们的拓扑结构是这样的:
https://foo.com -> [面向公众的代理] -> (https) -> [内部服务器 https://192...:8001]
如何配置 Gunicorn 以使用自签名证书侦听 HTTPS?
Gunicorn 现在支持 SSL,从 17.0 版本开始。您可以将其配置为像这样在 https 上侦听:
$ gunicorn --certfile=server.crt --keyfile=server.key test:app
如果您使用
--bind
监听端口 80,请记住将端口更改为 443(HTTPS 连接的默认端口)。例如:
$ gunicorn --certfile=server.crt --keyfile=server.key --bind 0.0.0.0:443 test:app
回复很晚,但对于其他遇到此问题的人,还有另一种选择使用 nginx 作为上面的“[面向公众的代理]”。
配置 nginx 以处理端口 443 上的传入 SSL 流量,然后 proxy_pass 到内部端口上的 gunicorn。外部流量是加密的,nginx 和 gunicorn 之间的流量无论如何都不会暴露。我发现这很容易管理。
如果您使用的是 gunicorn.config.py 或类似的 gunicorn 配置文件,您可以添加证书文件和密钥文件。
certfile = '/etc/letsencrypt/live/example.com/fullchain.pem'
keyfile = '/etc/letsencrypt/live/example.com/privkey.pem'
Config 文件可用于将设置初始化为 env 变量,如果您有很多设置,这会很有帮助。 使用配置文件
通过创建名为的文件来创建配置文件
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"'
当然
certfile = '/etc/letsencrypt/live/example.com/fullchain.pem'
keyfile = '/etc/letsencrypt/live/example.com/privkey.pem'
使用这些设置运行 gunicorn
$ gunicorn app:app
因为
默认情况下,将从运行 gunicorn 的同一目录中读取名为 gunicorn.conf.py 的文件。
除了
certfile
和keyfile
之外,您还需要添加ca-certs
。没有通过ca-certs
,我在Android设备上获得Trust anchor for certification path not found.
。
示例命令:
/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
ngrok
这样的安全隧道服务。使用 ngrok
,您可以轻松地从您的 gunicorn
服务器到他们提供的 https
启用的端点。
非常非常容易使用 - 我个人觉得
nginx
对于第一次使用来说有点复杂。
使用
ngrok
就像(安装后)一样简单:
gunicorn -b 0.0.0.0:4000
ngrok http 4000
这为您提供了一个像
https://abcd.ngrok.io
这样的安全端点,您可以向其发送请求,就像您向 gunicorn
服务器发送请求一样。