【Rasbperry Pi】ngrokでローカル環境を公開

Table of Content

【RaspberryPi】ngrokでローカルで立ち上げたサーバを公開する

目的

ngrokという、localhostで動いているサーバーをLANの外部からでもアクセスできるようにするサービスを使うと、RaspberryPiのWebサーバを外部に公開できるようになります。非常に簡単で10分もあれば出来ます。

環境

Raspberry Pi 3 Model B
python 3.7.3
flask 1.0.2

ngrokのインストール

Raspberry Piにngrokをインストールします。

pi@raspberrypi:~ $ wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-arm.zip
pi@raspberrypi:~ $ unzip ngrok-stable-linux-arm.zip
pi@raspberrypi:~ $ sudo mv ngrok /usr/local/bin/
pi@raspberrypi:~ $ ngrok version
ngrok version 2.3.35

RaspberryPiでWebサーバを起動する

flaskでhello worldを表示するWebサーバのスクリプトを作成します。

# ~/flask/hello_world.py

from flask import Flask
app = Flask( __name__ )

@app.route('/')
def hello_world():
    return 'Hello World'

if __name__ == '__main__':
     app.run(host='0.0.0.0', port=5000, debug=True)

Webサーバを起動します。ポートは5000番です。

pi@raspberrypi:~ $ python ~/flask/hello_world.py
 * Serving Flask app "hello_world" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!

ngrokを起動

最後にngrokを起動し、先程起動したWebサーバをLANの外部からアクセスできるようにします。

pi@raspberrypi:~ $ ngrok http 5000

ngrok by @inconshreveable                                                                             (Ctrl+C to quit)                                                                                                                      Session Status                online
Session Expires               7 hours, 59 minutes
Version                       2.3.35
Region                        United States (us)
Web Interface                 http://127.0.0.1:4040
Forwarding                    http://520aa216.ngrok.io -> http://localhost:5000
Forwarding                    https://520aa216.ngrok.io -> http://localhost:5000

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00 

LAN外にあるPCからhttps://520aa216.ngrok.ioにアクセスすると、以下のようにRaspberry Piで起動したWebサーバにアクセスすることができました。

ngrok-access

コメントを残す

Scroll to top