Ubuntu16.04 部署Django1.10 apache2.4 mod_wsgi

来源:互联网 发布:国外大学 canvas 软件 编辑:程序博客网 时间:2024/05/22 07:04

Ubuntu16.04默认是装有Python3.5的,先安装pip

sudo apt-get install python3-pip

接着安装venv

sudo apt-get install python3-venv

安装apache2

sudo apt-get install apache2

安装mod_wsgi

sudo apt-get install libapache2-mod-wsgi-py3

在/var目录中创建DjangoWeb文件夹,然后在当前目录创建venv

python3 -m venv venv

把之前开发的Django程序拷贝过去,开发环境如果和部署环境一样的话,可以直接把开发环境的sit-packages下载的包直接拷贝过去。
在/etc/apache2/sites-available目录下创建djangoWeb.conf文件

<VirtualHost *:80>      ServerName www.software.com    ServerAlias software.com    ServerAdmin huangle63@163.com    DocumentRoot /var/DjangoWeb    Alias /favicon.ico /var/DjangoWeb/djangoWeb/static/img/favicon.ico    Alias /static/ /var/DjangoWeb/djangoWeb/static/    <Directory /var/DjangoWeb/djangoWeb/static>        Options All        AllowOverride All        Require all granted    </Directory>    Alias /media/ /var/DjangoWeb/media/    <Directory /var/DjangoWeb/media>        Options All        AllowOverride All        Require all granted    </Directory>    WSGIScriptAlias / /var/DjangoWeb/djangoWeb/wsgi.py    <Directory /var/DjangoWeb/djangoWeb>        <Files wsgi.py>            Require all granted        </Files>    </Directory>    <Directory />        Options All        AllowOverride All        Require all granted    </Directory></VirtualHost>

修改Django项目中的wsgi.py文件

"""WSGI config for djangoWeb project.It exposes the WSGI callable as a module-level variable named ``application``.For more information on this file, seehttps://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/"""import os,sysfrom os.path import join,dirname,abspathos.environ["DJANGO_SETTINGS_MODULE"] = "djangoWeb.settings"sys.path.append('/var/DjangoWeb/venv/lib/python3.5/site-packages')PROJECT_DIR = dirname(dirname(abspath(__file__)))if PROJECT_DIR not in sys.path:    sys.path.insert(0,PROJECT_DIR)from django.core.wsgi import get_wsgi_applicationapplication = get_wsgi_application()

启动apache2服务

/etc/init.d/apache2 start

使配置文件djangoWeb.conf生效

sudo a2ensite djangoWeb.conf

使默认配置文件失效(否则局域网内其他电脑不能通过IP地址访问)

sudo a2dissite 000-default.conf

重启Apache

sudo /etc/init.d/apache2 restart

修改hosts文件
修改/etc下hosts文件,添加127.0.0.1 www.software.com

在setting.py中加入i自己允许的域名或者ip地址(这个地方切记加入自己的域名否则会报错)

ALLOWED_HOSTS = ['127.0.0.1', 'localhost',‘yourip_OR_domain’]

重启Apache服务器

sudo /etc/init.d/apache2 restart

验证配置
在浏览器中输入192.168.62.128(即本机IP地址)或者www.software.com都能显示Django的It works!页面

服务器出错的话,一定要多看看apache2的err log
命令行输入:

tail /var/log/apache2/error.log

官方文档
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/

Permission denied 的错误
http://blog.csdn.net/qingyuanluofeng/article/details/48978283

把venv拷贝到服务器方法:
现在服务器指定文件夹安装venv(python3 -m venv venv),之后把事先准备好的venv lib文件夹里的sit-packages文件夹拷贝到服务器相同目录即可
使用ftp方式上传venv时,先删除lib文件夹里的python3.5文件夹,之后把测试使用的文件夹拷贝到服务器,执行需要执行 ‘chmod 777 -R /var/DjangoWeb/’赋予读写权限

0 0