nginx+uwsgi+django是我们常用的django部署方式。nginx作为最前端的服务器,他负责接收所有的客户端请求,对于请求的静态文件,由nginx服务器自己完成,因为它具有很好处理静态文件的能力,性能进行过优化,支持高并发量;uWSGI服务器作为支持服务器,是用来服务nginx的,nginx将请求的动态文件交给uWSGI进行处理。uWSGI实现了uwsgi、wsgi和http协议,uwsgi协议是uWSGI自定义的协议,定义的是框架(django)和服务器对接的接口。
1.安装项目环境
系统环境:ubuntu16.04
python环境:python3.5.2
Django版本:django1.11.7
nginx环境:nginx_1.10.3
虚拟环境:virtualenv15.1.0
uwsgi版本:uwsgi2.0.17.1
安装并进入项目虚拟环境:
sudo apt-get install virtualenvvirtualenv -p python3 env_my_project source env_my_project/bin/activatepip install -r requirements.txt
2.项目配置及运行测试
修改项目配置文件:
cp my_project/settings_local.py.example my_project/settings_local.py
修改es配置文件:
cp rs_es/es_settings.py.example rs_es/es_settings.py
wsgi.py:
import osfrom django.core.wsgi import get_wsgi_applicationos.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings_local")application = get_wsgi_application()
项目运行测试:
python manage.py collectstatic # 收集静态文件python manage.py makemigrationspython manage.py migratepython manage.py runserver 0.0.0.0:8001
3.NGINX和UWSGI相关配置
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/my_projectsudo ln -s /etc/nginx/sites-available/my_project /etc/nginx/sites-enabled/sudo vim /etc/nginx/sites-enabled/my_project
nginx配置:
upstream my_project{ server unix:///var/run/my_project.sock;}server { listen 8001; //服务的端口号 服务通过nginx与uwsgi通信来启动 server_name 192.168.xx.xx; //nginx代理的ip charset utf-8; # max upload size client_max_body_size 10M; # send all non-media requests to the Django server. location / { uwsgi_pass my_project; include /etc/nginx/uwsgi_params; } location /static/ { root /home/ubuntu/my_project; }}
Uwsgi配置:
sudo mkdir /var/log/uwsgisudo chmod -R 777 /var/log/uwsgiuwsgi.ini:[uwsgi]chdir=/home/ubuntu/my_projecthome=/home/ubuntu/my_project/env_my_projectmodule=my_project.wsgi:applicationsocket=/var/run/my_project.sockchmod-socket = 666master=Trueprocesses = 5max-requests=5000# clear environment on exitvacuum=Truepidfile=/var/run/my_project.piddaemonize=/var/log/uwsgi/my_project.log# git pull 自动重启服务touch-reload=.git/index
4.配置Emperor mode监听和系统自动启动uwsgi
配置Emperor mode监听
sudo mkdir /etc/uwsgisudo mkdir /etc/uwsgi/vassalssudo ln -s /home/ubuntu/my_project/uwsgi.ini /etc/uwsgi/vassals/
系统自动启动uwsgi
sudo vim /etc/rc.local/usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals
5.通过uwsgi启动django服务
启动uwsgi
重启nginx
sudo service nginx restart
启动django服务
sudo uwsgi --reload /var/run/my_project.pid
此时在浏览器通过ngnix代理出来的ip和端口即可访问服务
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。
注:相关教程知识阅读请移步到服务器教程频道。