0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google Colab で Streamlit を ngrok 経由で公開する方法(2025年版)

Posted at

はじめに

これまで Google Colaboratory で Streamlit を動かす際は,

!streamlit hello & sleep 3 && npx localtunnel --port 8501

のように localtunnel を使う方法が一般的でした。
しかし近年の Colab 側のセキュリティ強化により,

  • npx 実行が失敗する
  • トンネルが確立できない
  • 外部公開 URL が取得できない

といった問題が発生するようになりました。

そこで本記事では、ngrok(pyngrok)を使った安定した方法を紹介します。

全体の流れ

  1. 必要なライブラリをインストール
  2. Streamlit アプリを作成
  3. .env に ngrok のトークンを設定
  4. ngrok でポートを公開
  5. Streamlit を起動

Google Colab で Streamlit を ngrok 経由で公開する方法(2025年版)

1. 必要なライブラリのインストール

Colab のセルで以下を実行します。

!pip install -q streamlit python-dotenv pyngrok
  • streamlit : Web アプリ本体
  • python-dotenv : .env ファイル読み込み用
  • pyngrok : Python から ngrok を操作

2. Streamlit アプリを作成

%%writefile app.py
import streamlit as st

st.title("Streamlit on Google Colab 🚀")
st.write("ngrok 経由で公開しています!")

3. 環境設定ファイル .env を作成

.env を作る

%%writefile .env
NGROK_TOKEN=

トークンを設定する

  1. 左側の ファイル一覧 を開く
  2. .env をクリック
  3. 以下のように 自分の ngrok トークン を入力して保存
NGROK_TOKEN=xxxxxxxxxxxxxxxxxxxx

🔑 ngrok のトークンは
https://dashboard.ngrok.com/get-started/your-authtoken
から取得できます(無料プラン可)

4. .env から NGROK_TOKEN を読み込む

import os
from pyngrok import ngrok
from dotenv import load_dotenv

load_dotenv(".env", override=True)

token = os.getenv("NGROK_TOKEN")

ngrok に認証トークンを登録

!ngrok authtoken $NGROK_TOKEN

5. ngrok でポートを公開し、Streamlit を起動

Streamlit のデフォルトポートは 8501 です。

public_url = ngrok.connect(8501).public_url
print(f"公開URL: {public_url}")

Streamlit を起動します。

!streamlit run app.py

実行結果

  • Colab の出力に 公開 URL が表示される
  • ブラウザでアクセスすると Streamlit アプリが表示される

🎉 Colab 上の Streamlit を外部公開できました!

よくある注意点

Streamlit が起動しない場合

  • すでに 8501 番ポートが使われていないか確認
  • ランタイムを再起動して再実行

ngrok が止まる

  • 無料プランでは セッション時間制限あり
  • 再接続すれば OK

localtunnel が動かない理由

  • Colab のセキュリティポリシー変更により
    • npx 実行
    • 一部外部プロセス
      が制限されているため

まとめ

  • localtunnel は現在の Colab では不安定
  • ngrok + pyngrok を使うと安定して Streamlit を公開可能
  • .env を使うことで トークン管理も安全

Colab で Streamlit を使う場合は、
👉 ngrok が現時点でのベストプラクティス です。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?