Django+Apache+mod_wsgi deployment under Ubuntu

Keywords: Django Apache sudo Python

OS: Ubuntu16.04LTS
Django: 1.11
Python: 2.7.11
Apache: 2.4

This article is just a simple deployment of Django+Apache
First, put the Django Project in the / var/www directory

1. Install Apache and mod_wsgi

sudo apt-get install apache2
sudo apt install libapache2-mod-wsgi
pip install virtualenv

2. Modify Django wsgi.py

import os
import sys

from django.core.wsgi import get_wsgi_application

PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, PROJECT_DIR)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = get_wsgi_application()

3. Create Apache configuration file

sudo vim /etc/apache2/sites-available/sitename.conf

The contents are as follows:

<VirtualHost *:80>
    ServerName 192.168.191.2
    ServerAlias otherdomain.com
    ServerAdmin example@163.com

    DocumentRoot /var/www/mysite    

    Alias /media/ /var/www/mysite/media/
    Alias /static/ /var/www/mysite/static/

    <Directory /var/www/mysite/media>
        Require all granted
    </Directory>

    <Directory /var/www/mysite/static>
        Require all granted
    </Directory>

    WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py
    WSGIDaemonProcess http://192.168.191.2 python-path=/var/www/mysite:/home/dang/pywork/webenv/lib/python2.7/site-packages
    WSGIProcessGroup http://192.168.191.2

    <Directory /var/www/mysite/mysite>
    <Files wsgi.py>
        Require all granted
    </Files>
    </Directory>
    #ErrorLog ${APACHE_LOG_DIR}/error.log
    #CustomLog ${APACHE_LOG_DIR}/access.logcombined
</VirtualHost>

Since I am using a virtualenv environment, I need to add the following to the above configuration file:

WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py
WSGIDaemonProcess http://192.168.191.2 python-path=/var/www/mysite:/home/dang/pywork/webenv/lib/python2.7/site-packages
WSGIProcessGroup http://192.168.191.2

Enable configuration files

sudo a2ensite sitename.conf

Restart Apache server

sudo service apache2 restart

Now you can go and visit.
Note: If the project uses sqllite database or there is an upload directory under the directory, the modification permissions need to be set.

Posted by vbnullchar on Thu, 07 Feb 2019 16:03:16 -0800