Ubuntu下Django+uWSGI+nginx部署

时间:2025-02-17 16:35:50

本文采用uwsgi+nginx来部署django

这种方式是将nginx作为服务端前端,将接受web所有的请求,统一管理,Nginx把所有的静态请求自己处理,然后把所有非静态请求通过uwsgi传递给Django,由Django来处理,从而完成一次web请求。

uwsgi

pip3 install uwsgi

测试:uwsgi --http :8080 --module mall.wsgi

http : 协议类型和端口号

processes : 开启的进程数量

workers : 开启的进程数量,等同于processes(官网的说法是spawn the specified number ofworkers / processes)

chdir : 指定运行目录(chdir to specified directory before apps loading)

wsgi-file : 载入wsgi-file(load .wsgi file)

stats : 在指定的地址上,开启状态服务(enable the stats server on the specified address)

threads : 运行线程。由于GIL的存在,我觉得这个真心没啥用。(run each worker in prethreaded mode with the specified number of threads)

master : 允许主进程存在(enable master process)

daemonize : 使进程在后台运行,并将日志打到指定的日志文件或者udp服务器(daemonize uWSGI)。实际上最常用的,还是把运行记录输出到一个本地文件上。

pidfile : 指定pid文件的位置,记录主进程的pid号。

vacuum : 当服务器退出的时候自动清理环境,删除unix socket文件和pid文件(try to remove all of the generated file/sockets)

四.Nginx+uwsgi+Django

Params uwsgi_params

Nginx配置文件 nginx.conf

uwsgi配置文件 uwsgi.ini

配置uwsgi

新建uwsgi.ini文件

[uwsgi]

socket = :8000 # 端口号

master = true # 允许主进程存在

processes = 4

workers = 5 # 进程个数

enable-threads = true

post-buffering = 4096

chdir = /root/masami/luntan # 项目所在路径

home = /root/masami/env # 项目的虚拟环境

module = luntan.wsgi:application

vacuum = true

socket = /root/masami/uwsgi.sock # uwsgi.sock文件存放目录

运行

uwsgi --ini uwsgi.ini

Nginx

Nginx安装

sudo apt-get install nginx

基本命令

/etc/init.d/nginx start # 启动

/etc/init.d/nginx stop # 关闭

/etc/init.d/nginx restart # 重启

网站的日志文件

mkdir /var/log/nginx/masami/ # 新建文件夹来存放网站的日志文件

配置文件

进入 /etc/nginx/sites-availabel下

在这个文件夹下新建不同站点的配置文件

修改default文件的端口

touch masami # 新建masami文件,作为本项目的配置文件


server {
listen 80;
server_name localhost;
charset utf-8; client_max_body_size 75M; # 这块存让日志文件
access_log /var/log/nginx/masami/Masami_access.log;
error_log /var/log/nginx/masami/Masami_error.log; location /media {
alias /root/masami/luntan/media;
} location /static {
alias /root/masami/luntan/static;
} location / {
uwsgi_pass 127.0.0.1:8000;
include /etc/nginx/uwsgi_params;
}
}

检查nginx语法是否错误 nginx -t

出现静态资源403的错误

修改/etc/nginx/nginx.conf 文件

将第一行改为user root;

重启nginx

supervidor

安装

supervidor 仅支持python2

配置文件

echo_supervisord_conf > /etc/supervisord/supervisord.conf