Harvard_Fly 阅读(17) 评论(0)

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 virtualenv
virtualenv -p python3 env_my_project 
source env_my_project/bin/activate
pip 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 os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings_local")
application = get_wsgi_application()

项目运行测试:
python manage.py collectstatic # 收集静态文件
python manage.py makemigrations
python manage.py migrate
python manage.py runserver 0.0.0.0:8001

3.NGINX和UWSGI相关配置

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/my_project
sudo 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/uwsgi
sudo chmod -R 777 /var/log/uwsgi

uwsgi.ini:
[uwsgi]
chdir=/home/ubuntu/my_project
home=/home/ubuntu/my_project/env_my_project
module=my_project.wsgi:application

socket=/var/run/my_project.sock
chmod-socket = 666

master=True
processes = 5
max-requests=5000

# clear environment on exit
vacuum=True

pidfile=/var/run/my_project.pid
daemonize=/var/log/uwsgi/my_project.log

# git pull 自动重启服务
touch-reload=.git/index

4.配置Emperor mode监听和系统自动启动uwsgi

配置Emperor mode监听
sudo mkdir /etc/uwsgi
sudo mkdir /etc/uwsgi/vassals
sudo 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
uwsgi --ini uwsgi.ini

重启nginx
sudo service nginx restart

启动django服务
sudo uwsgi --reload /var/run/my_project.pid

此时在浏览器通过ngnix代理出来的ip和端口即可访问服务