LoginSignup
4
4

More than 5 years have passed since last update.

Django x Apache x mod_wsgiの環境をVagrant(Ubuntu16.04)でつくる

Posted at

PythonをApacheとかNginxとかのWEBサーバで動かす場合は、WSGIという仕組みを間にかませる必要があります。WSGIの仕組みはシンプルなようですが、まだ詳しく調べてはいないです。WSGIを間にかませることから、PHPよりはちょっとめんどくさいです。でも一度覚えれば準備工数に差はほとんどありません。この投稿では、VagrantのUbuntu16.04上で、DjangoとApacheでWEBアプリケーションを動作させるようにしてみます。今回はPyenvは入れずに、既にインストール済みのPython3.5を使って設定します。

環境

  • Windows10
  • Vagrant 1.9.3
  • Ubuntu16.04
  • Python 3.5.2
  • Apache/2.4.18 (Ubuntu)

Vagrantfileの設定

Ubuntu 16.04のボックス(ubuntu/xenial64)を使います。

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/xenial64"
  config.vm.network "forwarded_port", guest: 80, host: 9090, host_ip: "127.0.0.1"
end

Vagrantを立ち上げて入る

$ vagrant up
$ vagrant ssh

Apache2をインストール

$ sudo apt-get update
$ sudo apt-get install -y vim apache2 apache2-dev

mod_wsgiをインストール

$ sudo apt-get install -y libapache2-mod-wsgi-py3

Djangoをインストールして、アプリを作成する

$ sudo apt-get install -y python3-pip
$ sudo pip3 install --upgrade pip
$ sudo pip3 install django
$ mkdir /vagrant/django
$ cd /vagrant/django
$ django-admin startproject mysite

apache2の設定

django.confを作る

/etc/apache2/sites-available/django.confを新たに作成します。

/etc/apache2/sites-available/django.conf
<VirtualHost *:80>
  WSGIDaemonProcess mysite python-home=/usr python-path=/vagrant/django/mysite
  WSGIScriptAlias / /vagrant/django/mysite/mysite/wsgi.py process-group=mysite
  <Directory /vagrant/django/mysite/mysite>
    <Files wsgi.py>
      Require all granted
    </Files>
  </Directory>
</VirtualHost>

WSGIの各パラメタは大体下記のような感じ。ここに詳細のマニュアルがあるので、不明点やエラーが出る場合はこれを頑張って読む必要がある。

  • WSGIDaemonProcessのpyhton-homeは、下記で確認できる。
 $ python3
 >>> import sysconfig
 >>> sysconfig.get_config_var('prefix')
'/usr'
  • python-pathは、Djangoプロジェクトのルートフォルダのパス。
  • WSGIScriptAliasは、最初の/が、アプリケーションのベースとなるURLパス。/の場合はWEB ROOTになる。2番目の部分は、WSGI fileの場所。

django.confを有効化させる

デフォルト設定を無効化し、django.confを有効化させます。

$ sudo a2dissite 000-default
$ sudo a2ensite django

apache2を再起動します。

$ sudo systemctl restart apache2
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4