静的ファイルのデプロイ

参考

django.contrib.staticfiles の使い方の基本に関しては、静的ファイル (画像、JavaScript、CSS など) を管理する を読んでください。

本番環境における静的ファイルの配信

The basic outline of putting static files into production consists of two steps: run the collectstatic command when static files change, then arrange for the collected static files directory (STATIC_ROOT) to be moved to the static file server and served. Depending on STATICFILES_STORAGE, files may need to be moved to a new location manually or the post_process method of the Storage class might take care of that.

どんなデプロイのタスクでも、悪魔は細部に宿るものです。(訳注: Devil's in the detail。神は細部に宿る (God is in the detail) から派生したことわざ) それぞれの本番環境でセットアップには僅かに違いがあるものなので、基本的な流れに沿うように多少の手直しが必要になるかもしれません。以下によくあるパターンを紹介しているので、参考にしてください。

サイトと静的ファイルを同じサーバから配信する

静的ファイルをすでにサイトを配信しているのと同じサーバから配信したい場合、配信の手順は次のようになります。

複数の Web サーバーがある場合は、おそらくこのプロセスを自動化したいと思うでしょう。

専用のサーバから静的ファイルを配信する

比較的大きな Django サイトでは、Django を実行しているのとは異なる専用のサーバを用意して、静的ファイルを配信するのがふつうです。こうした専用サーバでは、高速なサーバや機能を限定したサーバなど、普通の Web サーバとは異なる種類のサーバを利用します。よくある選択肢としては、次のものが挙げられます。

これらのサーバの設定方法は、このドキュメントの範囲外です。それぞれのサーバのドキュメントを参考に設定してください。

静的ファイルサーバでは Django が実行されていないので、次のようにデプロイの戦略を変更する必要があります。

  • 静的ファイルが変更されたら、ローカル側で collectstatic を実行する。
  • ローカル側の STATIC_ROOT を静的ファイルサーバのファイル配信ディレクトリにアップロードします。これには、rsync を使用するのが一般的です。rsync を利用すれば、変更された静的ファイルの情報だけを転送することができます。

クラウドサービスや CDN から静的ファイルを配信する

もう一つのよく用いられる方法は Amazon の S3 や CDN (コンテンツ・デリバリー・ネットワーク) のようなクラウドストレージから静的ファイルを利用する方法です。この方法では静的ファイルの取扱いに関する問題を無視できるようにし、(特に CDN を利用している場合は) しばしば Web ページの高速なローディングの助けとなります。

これらのサービスを使う場合でも、基本的なワークフローは上で説明した通りです。ただし、rsync を使って静的ファイルをサーバに転送する代わりに、ストレージプロバイダや CDN に転送する必要があります。

There's any number of ways you might do this, but if the provider has an API, you can use a custom file storage backend to integrate the CDN with your Django project. If you've written or are using a 3rd party custom storage backend, you can tell collectstatic to use it by setting STATICFILES_STORAGE to the storage engine.

たとえば、S3 storage backend を myproject.storage.S3Storage としてすでに書いていれば、次のように書くだけでこのストレージを利用できます。

STATICFILES_STORAGE = 'myproject.storage.S3Storage'

Once that's done, all you have to do is run collectstatic and your static files would be pushed through your storage package up to S3. If you later needed to switch to a different storage provider, you may only have to change your STATICFILES_STORAGE setting.

For details on how you'd write one of these backends, see カスタムストレージシステムの作成. There are 3rd party apps available that provide storage backends for many common file storage APIs. A good starting point is the overview at djangopackages.org.

さらに学ぶ

すべての設定、コマンド、テンプレートタグなどの詳細と、django.contrib.staticfiles に含まれているその他の機能については、staticfiles リファレンス を読んでください。