Djangoのdeployに関する覚え書き

以下、Ubuntu 14.04.2 LTS (trusty)稼働サーバへの配備を試みた。

1. Pythonのバージョンを統一し、実行環境を指定

例えば/usr/local/anaconda3/bin/pythonを実行ファイルとするPython 3.4を使うなら、
(1) mod_wsgiPython 3.4対応になっているか、また、適切なPythonライブラリを指しているか、ldd /usr/lib/apache2/modules/mod_wsgi.so等で確認する。
(2) Pythonインストール場所ホームディレクトリ・開発環境ホームディレクトリを/etc/apache2/mods-enabled/wsgi.conf等の設定ファイル中に、

WSGIPythonHome /usr/local/anaconda3
WSGIPythonPath /home/taro/MyDjangoSystem

のような形で記述する。

2. mod_wsgiの読み込み

/etc/apache2/mods-enabled/wsgi.load等に

LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so

等の記述があるか、確認。

3. サイトの設定

/etc/apache2/sites-enabled/000-default.conf等の<VirtualHost *:80>の中で、

# Comments within <Directory>...</Directory> not allowed?
# Don't put Options +ExecCGI as the script should be executed via mod_wsgi.
# Does the order of the following statements matter?

Alias /MySystem_static/ /home/taro/MyDjangoSystem/static/

<Directory /home/taro/MyDjangoSystem/static/>
Require all granted
</Directory>

WSGIScriptAlias /MySystem /home/taro/MyDjangoSystem/MyDjangoSystem/django.wsgi

<Directory /home/taro/MyDjangoSystem/MyDjangoSystem>
<Files django.wsgi>
Require all granted
</Files>
</Directory>

元々wsgi.pyが用意されていると思われるが、cgiスクリプトと混同される可能性があるので、django.wsgi等へコピーし、上記のように記述。

4. settings.pyの記述

(1) デバッグモードを無効にする。

DEBUG = False

(2) アクセスを許可するホストを指定。ホストの制限を設けないなら、

ALLOWED_HOSTS = ['*']

(3) 一部URLパスの設定が必要。例えば、

LOGIN_URL = "MySystem" + "/login/"

STATIC_URL = "/MySystem_static/"

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
] # Intended to be used by both test and actual server

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, "MySystemDB", 'db.sqlite3'), # Initialization by migration required.
    }
}

等。

(settings.pyの更新がうまく反映されないときがあった。ファイルの更新日付が関係あるのだろうか。(touch settings.pyを試す?) それとも改行コード?)

5. ディレクトリやファイルのpermissionの設定

例えば、sqlデータベースのパーミッションやそれが配置されているディレクトリのパーミッションを適切に設定する必要がある。

6. apacheの再起動

sudo /etc/init.d/apache2 restart

7. 注意

以下のようなエラーが出たときは、その下のページを参照。
AssertionError:
Exception ignored in: <module 'threading' from '/usr/local/lib/python3.4/threading.py'>
assert tlock is not None


※ URLの最初・最後のスラッシュ'/'の有無に十分注意。本サイトの記述は必ずしも正確ではない。

8. 今後の課題
(1) 本運用環境(mod_wsgiembedded mode)では、設定を変更するたびにapacheを再起動する必要がある。daemon modeによる運用を考慮すべき。
(2) virtualenvを有効にすることを考慮すべき。