您的位置:首页 >聚焦 >

头条:使用 nginx + gunicorn 来部署生产环境的 Django app

2022-08-09 06:47:38    来源:程序员客栈

在测试环境下,我们可以简单的使用 python manage.py runserver 8080启动一个 Django,由于尚未通过安全审核或性能测试,而且是单线程,并发能力也不强,因此不能在生产环境中使用。

生产环境下,需要使用专门的 Web 服务器,像 Gunicorn 或 uWSGI。

今天就来分享一下如何使用 nginx + gunicorn 来部署生产环境的 Django app。


(相关资料图)

Gunicorn(Green Unicorn)是一个用于 UNIX 的 Python WSGI HTTP 服务器。Gunicorn 服务器广泛兼容各种 Web 框架,实现简单,服务器占用资源少,速度相当快。Django app 只是它支持的其中一种框架。

安装

pipinstallgunicorn

gunicorn 没有依赖项,因此下载后可以很容易迁移到生产环境。

快速使用

直接在 Django 项目的目录内,也就是 manage.py 所在的目录内执行:

gunicornyour_project.wsgi:application--bind0.0.0.0:8000

即可启动生产级别的 Web 服务,前提是你的 Django settings 也是生产环境的配置,例如 Debug = False。

配置成系统服务

首先让我们创建一个系统级别的套接字文件:

sudovim/etc/systemd/system/gunicorn.socket

写入以下内容:

[Unit]Description=gunicorn socket[Socket]ListenStream=/run/gunicorn.sock[Install]WantedBy=sockets.target

然后创建一个 Gunicorn 系统服务文件:

sudovim/etc/systemd/system/gunicorn.service

写入以下内容:

[Unit]Description=gunicorn daemonRequires=gunicorn.socketAfter=network.target[Service]User=hiteshGroup=www-dataWorkingDirectory=/home/hitesh/myprojectdirExecStart=/home/hitesh/myprojectdir/myprojectenv/bin/gunicorn \          --access-logfile - \          --workers 3 \          --bind unix:/run/gunicorn.sock \          myproject.wsgi:application[Install]WantedBy=multi-user.target

这样我们就可以在系统启动的时候启动 Gunicorn 服务,也可以很方面的启动、停止、重启 Gunicorn。

sudosystemctlenablegunicornsudosystemctlstartgunicornsudosystemctlstopgunicornsudosystemctlrestartgunicorn

查看服务状态:

sudosystemctlstatusgunicorn.socket

与 Nginx 配合

Nginx 非常适合处理静态文件,所以静态文件就交给 Nginx,然后服务接口交给 Gunicorn,让 Nginx 代理 Gunicorn。

一个简单的配置文件如下:

server {    listen 80;    server_name server_domain_or_IP;    location = /favicon.ico { access_log off; log_not_found off; }    location /static/ {        root /home/aaron/myprojectdir;    }    location / {        include proxy_params;        proxy_pass http://unix:/run/gunicorn.sock;    }}

测试配置文件是否有误:

sudonginx-t

如果没有错误,可以重启 Nginx 让新的配置文件生效:

sudonginx-sreload

你可能还需要配置你的证书。

Nginx 和 Gunicorn 故障排除

对于故障排除,日志可以帮助找到根本原因。检查以下日志可以帮助排除故障:

查看 Nginx 进程日志:sudo journalctl -u nginx

查看 Nginx 访问日志:sudo less /var/log/nginx/access.log

检查 Nginx 错误日志:sudo less /var/log/nginx/error.log

检查 Gunicorn 应用程序日志:sudo journalctl -u gunicorn

检查 Gunicorn 套接字日志:sudo journalctl -u gunicorn.socket

最后的话

本文分享了使用 nginx + gunicorn 来部署生产环境的 Django app,生产环境下 Nginx 的反向代理,最好都使用 socket 来通讯,至于为什么,可以参考前文redis 是单线程,是怎么解决高并发问题的。如有收获,还请在看支持。

关键词: 生产环境 配置文件 以下内容

相关阅读