Featured image of post Django 项目部署流程

Django 项目部署流程

环境: Ubuntu 20.04

在服务器配置Django项目

最常用的是从远程仓库clone一个项目

clone下来的项目属于一个正常的用户就行

然后使用 requirements.txt 安装所需要的包 (在服务器上)

pip install -r requirements.txt

如果你的项目中没有这玩意,记得生成一个 requirements.txt (在开发机器上)

pip list –format=freeze > requirements.txt

新建一个 /run/uwsgi 文件夹并将权限给 www-data用户(组)

sudo mkdir /run/uwsgi/
sudo chown -R www-data:www-data /run/uwsgi/

配置uWSGI

装一个uwsgi

sudo apt update
sudo apt install uwsgi

新建uwsgi.ini

在Django项目文件夹下新建一个 “uwsgi.ini”

[uwsgi]

uid= 'user' # your username
gid=www-data
project= 'your_project' # your project name
base=/home/%(uid)


chdir=%(base)/%(project)
# module=%(project).wsgi:application # 因为我的项目没有生成project.wsgi所以就用wsgi-file替代了
wsgi-file=%(project)/wsgi.py
socket=/run/uwsgi/%(project).sock

 
workers = 2 # 可以根据自己机器性能修改
threads = 4 # 可以根据自己机器性能修改


chown-socket=%(uid):%(gid)
chmod-socket=664

通过 uwsgi 启动 Django 服务

sudo uwsgi –ini uwsgi.ini

如果没有出现以下报错即可视为成功

*** Operational MODE: preforking+threaded ***
ModuleNotFoundError: No module named '[your project name]'
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***

如果出现上面的报错即表明文件权限有问题

uWSGI.ini 中 chown-socket 指定了uWSGI以什么用户身份启动。
如果 ModuleNotFundError 出现则很可能说明uWSGI进程无权限访问Django Project目录中的wsgi-file: 即wsgi.py

可能的解决办法

将当前用户加入 www-data 组

sudo [your username] -a -G www-data ubuntu 

再次确认 uWSGI 是以 your_username:www-data 的身份启动

在命令后面加 & 可以让 uwsgi 在后台运行

强制结束uWSGI进程

如果想结束后台运行的 uwsgi 的进程需要使用kill

killall -9 uwsgi

配置Nginx

在开发环境中我们常用http:127.0.0.1:8000来作为前后端交互的服务器。在生产环境可以用 uWSGI 生成 unix sock 以便Web服务器与uWSGI之间进行通信来提升效率

装一个Nginx

sudo apt update
sudo apt install nginx

修改 Nginx 配置文件

sudo vi /etc/nginx/sites-enabled/default
server {
    listen 80;
    server_name _;

    location /api {
        include uwsgi_params;
        uwsgi_pass unix:/run/uwsgi/[your project].sock;
    }
    location / {
        try_files $uri $uri/ /index.html;
    }

}

重启Nginx

sudo systemctl restart nginx

此时再将 uWSGI 在后台启动应该就可以了

Reference

https://pythondjango.cn/python/tools/6-uwsgi-configuration/
https://zhuanlan.zhihu.com/p/357289018

Licensed under CC BY-NC-SA 4.0
转载或引用本文时请遵守许可协议,知会作者并注明出处
不得用于商业用途!
Last updated on Jan 27, 2024 15:47