Django项目部署到Apache服务器

本文讲述的是在阿里云服务器(ECS)上部署Django项目于Apache,服务器操做系统为ubuntu,公网Ip地址为123.56.30.151。python

将Django部署到Apache服务器的缘由web

Django中的runserver只是一个很简单的web服务器,启动服务器常见的方法是经过Putty执行命令。虽然调试和测试方便,然而若是关闭了Putty或者退出命令,服务就中止了,而且不能承受许多用户同时使用的负载。因此须要将Django部署到生产级的服务器,这里选择Apache。sql

ubuntu上部署详细步骤数据库

1.安装apache2 apache

apt-get install apache2

2.测试apache2django

打开浏览器输入123.56.30.151(云服务器的IP)ubuntu

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.confapp

<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
相关文章
相关标签/搜索