Django项目部署到Apache服务器

本文讲述的是在阿里云服务器(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
原文地址:https://www.cnblogs.com/Junsept/p/6862595.html