django如果通过python3 manage.py runserver形式运行,内部调用的是wsgiref模块,运行的socket服务端,性能低下,单进程,单线程
使用nginx+ uwsgi进行项目部署
1.准备django项目 xxx
2.安装虚拟环境,在虚拟环境下,安装uwsgi,进行部署
workon nbcrm
pip3 install -i https://pypi.douban.com/simple uwsgi
3.利用uwsgi运行一个python web脚本文件
新建一个py脚本文件,写入如下内容
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"] # python3
启动命令如下
uwsgi --http :8000 --wsgi-file test.py
http参数意思是,基于http协议运行 在 8000端口
wsgi-file test.py: 加载指定的文件,test.py
4.利用uwsgi运行django项目
(以参数形式运行项目),(还有以配置文件形式运行,把运行的参数写入到一个文件里面,基于这个文件运行)
命令如下
uwsgi --http :8088 --module mysite.wsgi
–module 找到django项目的第二层里面的wsgi.py文件
uwsgi默认不支持静态文件解析,使用nginx去解析静态文件
5.热加载django项目,uwsig自动重启django
uwsgi --http :9000 --module NBcrm.wsgi --py-autoreload=1
6.基于配置文件的形式,运行nbcrm
uwsgi的配置文件
[uwsgi]
# Django-related settings
# the base directory (full path)
#项目的绝对路径,定位到nbcrm的第一层
chdir = /opt/NBcrm
# Django's wsgi file
# 找到项目第二层的wsgi文件
module = NBcrm.wsgi
# the virtualenv (full path)
# 找到虚拟环境的绝对路径
home = /root/Envs/nbcrm
# process-related settings
# master
# 主进程
master = true
# maximum number of worker processes
# 开启uwsgi的多进程数,根据cpu核数来定义
processes = 16
# the socket (use the full path to be safe
# 基于socket链接运行crm,只有与nginx结合的时候,才使用socket形式
socket = 0.0.0.0:8000
# 当你没用nginx,调试项目的时候,使用http形式
#http = 0.0.0.0:8000
# ... with appropriate permissions - may be needed
# chmod-socket = 664
# clear environment on exit
vacuum = true
#指定一个参数,日志放在哪
#如果你使用了supervisor,请注释掉这个参数
#守护进程在后台运行,且将日志信息,输出到uwsgi.log日志中
#daemonize = uwsgi.log
启动配置文件的命令
/root/Envs/nbcrm/bin/uwsgi --ini uwsgi.ini
7.配置nginx,结合uwsgi,以及处理静态文件的配置
nginx.conf请求转发配置如下
server {
listen 80;
server_name localhost;
location / {
include uwsgi_params;
uwsgi_pass 0.0.0.0:8000;
}
}
nginx处理crm的静态文件方式
1.修改django的settings.py静态文件,添加如下参数
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_ROOT='/opt/s20static'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'statics'),
]
2.执行命令,收集crm的静态文件
python3 /opt/NBcrm/manage.py collectstatic
3.配置nginx的location路径匹配,找到crm这些静态文件
在nginx.conf中找到server{}标签,添加如下参数
#当我的请求url是 192.168.16.142:80/static/xxxxxxxx
location /static {
alias /opt/s20static/;
}
4.启动nginx,访问nginx的80,是否可以转发到crm
8.使用supervisor进程管理工具,管理你的项目
其实,supervisor就是在帮你执行命令而已
使用supervisor管理进程,这个进程不得在后台运行