本文講述的是在阿里雲服務器(ECS)上部署Django項目於Apache,服務器操作系統為ubuntu,公網Ip地址為123.56.30.151。
將Django部署到Apache服務器的原因
Django中的runserver只是一個很簡單的web服務器,啟動服務器常見的方法是通過Putty執行命令。雖然調試和測試方便,然而如果關閉了Putty或者退出命令,服務就停止了,並且不能承受許多用戶同時使用的負載。所以需要將Django部署到生產級的服務器,這里選擇Apache。
ubuntu上部署詳細步驟
1.安裝apache2
apt-get install apache2
2.測試apache2
打開瀏覽器輸入123.56.30.151(雲服務器的IP)
3.建立python與apache的連接
apt-get install libapache2-mod-wsgi #通過執行python -V查看python版本,如果是3.0將第換為 apt-get install libapache2-mod-wsgi-py3
4.准備一個新網站
ubuntu的apache2配置文件在 /etc/apache2/ 下,在文件夾sites-available下新建一個網站配置文件:mysite.conf
<VirtualHost *:8888> DocumentRoot /var/www/mysite/mysite <Directory /var/www/mysite/mysite> Order allow,deny Allow from all </Directory> WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py </VirtualHost>
通過apachectl -v查看apache2版本號,如果是2.4.x,將Directory中的內容修改為
Require all granted
5.更改端口
修改ports.conf中的Listen 80為Listen 8000,注意:這個文件的開頭有一個提示
# If you just change the port or add more ports here, you will likely also # have to change the VirtualHost statement in # /etc/apache2/sites-enabled/000-default.conf
無需遵照這個提示,即不用修改000-default.conf中的端口號,默認為80.
6.更改django工程
在工程的wsgi.py文件中添加
import sys sys.path.append("/var/www/mysite/")
7.設置目錄和文件權限
一般目錄權限設置為 755,文件權限設置為 644
假如項目位置在 /var/www/mysite (在mysite下面有一個 manage.py,mysite是項目名稱)
cd var/www/ sudo chmod -R 644 mysite sudo find mysite -type d -exec chmod 755 \{\} \;
sqlite3數據庫讀寫權限:
sudo chgrp www-data mysite sudo chmod g+w mysite sudo chgrp www-data mysite/db.sqlite3 sudo chmod g+w mysite/db.sqlite3
8.配置生效
a2ensite mysite.conf
9.啟動服務
service apache2 restart
出現錯誤:
restarting web server apache2 [fail] * The apache2 configtest failed. Output of config test was: AH00526: Syntax error on line 8 of /etc/apache2/sites-enabled/mysite.conf: Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a module not included in the server configuration Action 'configtest' failed. The Apache error log may have more information. tony@T:/etc/apache2/sites-available$ sudo a2enmod wsgi ERROR: Module wsgi does not exist!
執行命令:
sudo apt-get purge libapache2-mod-wsgi
sudo apt-get install libapache2-mod-wsgi
出現錯誤:
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message
在apache2.conf文件末尾添加,這里的端口設置跟000-default.conf中的一樣,而不是mysite.conf中的端口。
ServerName localhost:80