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 [email protected]
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, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os,sys
from os.path import join,dirname,abspath
os.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_application
application = 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/’賦予讀寫權限