1つのホストで複数のDjangoプロジェクトを動かす
やりたいこと
- 1つのホストで複数のDjangoプロジェクトを動かしたい。
- 動作環境は Gunicorn + nginx とする。
- セキュリティは考慮しない。
方針
- Gunicornをプロジェクトごとにポートを変えて起動する
- nginxのリバースプロキシ設定で、URLごとに接続先gunicornのポートを振り分ける
動作検証用Djangoプロジェクト
プロジェクト site1, アプリケーション hello
hello/views.py
from django.http import HttpResponse def hello(request): return HttpResponse("Hello !")
site1/urls.py
urlpatterns = [ path("admin/", admin.site.urls), path("", hello) ]
site1/settings.py
ALLOWED_HOSTS = ["localhost", "127.0.0.1"] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "hello", # ★追加 ]
プロジェクト site2, アプリケーション world
world/views.py
from django.http import HttpResponse def world(request): return HttpResponse("World !")
site2/urls.py
urlpatterns = [ path("admin/", admin.site.urls), path("", world) ]
site2/settings.py
ALLOWED_HOSTS = ["localhost", "127.0.0.1"] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "world", # ★追加 ]
Gunicornの起動
site1とsite2でポートを変えて起動する。
$ gunicorn --bind localhost:8001 site1.wsgi $ gunicorn --bind localhost:8002 site2.wsgi
nginxの設定
$ sudo vim /etc/nginx/conf.d/site.conf
/site1 をポート8001に、/site2 をポート8002に結びつける。
server { listen 80; location /site1 { proxy_pass http://localhost:8001; } location /site2 { proxy_pass http://localhost:8002; } }
※↓環境次第ではいらないかも(WSLのUbuntu 20.04LTSでは必要だった)
$ sudo rm /etc/nginx/sites-enabled/default
nginxリロード
$ nginx -s reload
ブラウザで表示確認
- http://localhost/site1/
- site1のhelloアプリが表示
- http://localhost/site2/
- site2のworldアプリが表示