【無料】Ruby で Cloud Run を使って API を作ってみた
概要
コンテナをサーバレス like に使える Cloud Run。
今までのサーバレスの課題(制約)
を解決できる。
ポケモンGOで、特定の位置に★5レイドが出現しているか調べる API を作ってみた。 (※外部のAPIを使っているので、いつの間にか使えなくなってるかも...)
言語は Ruby。
料金
今回使った GCP リソースは
- Cloud Run
- Container Registry
- Cloud Storage
- Cloud Build
で全部のはず。
Container Registry の料金 | Container Registry | Google Cloud
Container Registry は Docker イメージに使用する Cloud Storage の費用のみ。
GCP Free Tier | Google Cloud Platform Free Tier | Google Cloud
Always Free(無料枠)で Cloud Storage、Cloud Build は事足りそう。
Pricing | Cloud Run Documentation | Google Cloud
Cloud Run も無料枠があり、自分1人で使うものなので、事足りそう。
ということで、おそらく無料で済むかと。(もしお金がかかっていたら追記します。)
手順
ドキュメントはこのあたり。
Cloud Build、Cloud Run の API が有効になっていなければ、有効にする。
Container Registry に Docker image をあげる
gcloud builds submit --tag gcr.io/$GCP_PROJECT_ID/pokemon-go-raid-appearance --project $GCP_PROJECT_ID
Cloud Run にデプロイ
gcloud beta run deploy pokemon-go-raid-appearance --image gcr.io/$GCP_PROJECT_ID/pokemon-go-raid-appearance --project $GCP_PROJECT_ID --set-env-vars THIRD_PARTY_ENDPOINT="http://127.0.0.1",BASE_LAT="35.681236",BASE_LNG="139.767125"
API エンドポイントへアクセス。https://XXXXXXXXX.run.app
終わり。
非常に簡単に API を公開できた。
ハマったこと
とはいえ、いくつかハマった。
その1
ERROR: (gcloud.beta.run.deploy) Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.
その時のコードはこちら。
Webサーバーを立ち上げる必要があるらしい。
sinatra を使うことに。
リクエストをトリガーにスクリプトを一回実行できる、今までのサーバレスの課題を解決したものがあれば、もっと便利そうだなー。
その2
CORS。
無事にアクセスできた。
所感
Cloud Run は仕事でもプライベートでももっともっと活用していこうと思った。
今回の「ポケモンGOのレイド出現アプリケーション」は後ほどアクセス制限して、セキュリティ高めよう。
また View も google map に表示する等にしようと思う。