LoginSignup
3
4

More than 3 years have passed since last update.

ngrokを使ってdjangoアプリを限定公開する

Last updated at Posted at 2020-04-22

目的

djangoアプリを限定的かつ手軽に公開するため、
ngrokを使ってローカルで起動しているdjangoアプリを外部から利用する。

ngrokとは

ngrokとは、localhostで動いているサーバーを、LANの外からアクセスできるようにできるツールです。
詳細は→ngrokの使い方(windows, mac)

ngrokの起動

ngrokを↓からダウンロードし、任意の場所で解凍する。
ngrok

ngrok.exeを起動する
ngrok.exe.png

ngrokの設定

djangoをデフォルトで起動した場合、ポート番号は8000となる。

System check identified no issues (0 silenced).
April 22, 2020 - 17:50:03
Django version 3.0.3, using settings 'project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

アプリのURLhttp://127.0.0.1:8000/をngrokで処理するため
ngrokのターミナル上で、ngrok http 8000を入力して実行する。
ngrok.exeに引数を渡して実行するのも〇
ngrok.exe http 8000
ngrok.exe2.png

Forwardingに表示されてるxxxxx.ngrok.io/アプリ名で外部アクセスができる。
アプリ名はapps.pyで定義したアプリケーション名。

djangoの設定

djnago側ではngrokからのアクセスを許可する必要があり、ALLOWED_HOSTS'.ngrok.io'を追記する。
.ngrokの前の文字列は起動の度にランダム生成されるため、起動時に影響しないようngrokからのアクセスのみを許可する。

settings.py
ALLOWED_HOSTS = ['.ngrok.io']

ALLOWED_HOSTSの対応をしなかった場合には下記のエラーが発生する。

DisallowedHost at /app/
Invalid HTTP_HOST header: 'xxxxx.ngrok.io'. You may need to add 'xxxxx.ngrok.io' to ALLOWED_HOSTS.

Request Method: GET
Request URL:    http://xxxxx.ngrok.io/app/
Django Version: 3.0.3
Exception Type: DisallowedHost
Exception Value:    
Invalid HTTP_HOST header: 'xxxxx.ngrok.io'. You may need to add 'xxxxx.ngrok.io' to ALLOWED_HOSTS.
・
・
・

3
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
3
4