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 がサポートする Python ランタイムを使用して Cloud Run にソースからアプリケーションをデプロイする方法

Last updated at Posted at 2024-09-25

Google Cloud の利用下では、Dockerfile を使って FROM 句で DockerHub から Python 付きのイメージを pull するよう記述してデプロイする方式では Python に関する問題についてサポートを受けられないことがわかりました。

サポートを受けるためには Google のサポートしているランタイムを使用する必要があり...
https://cloud.google.com/run/docs/configuring/services/runtime-base-images?hl=ja

リファレンスのつなぎ合わせとサポートへの問い合わせとでやっとたどり着いた。
上から下まで一連で書かれているページがないので書き残しておく。

前提条件

・デプロイ直後のトラフィックが 0% になるようにし、デプロイ直後に新旧が入れ替わらないように配慮
・Python3.11 で固定する
・使用する Google の Builder を google-22 で固定する

1 Python のバージョン固定

ソースディレクトリ直下に .python-version という名前でファイルを置く
中身は以下

3.11

2 gunicorn の起動設定

ソースディレクトリ直下に Procfile という名前でファイルを置く
以下は中身の例

web: gunicorn --bind :$PORT --workers 2 --timeout 300 main:app

3 ビルダーの固定

ソースディレクトリ直下に project.toml という名前でファイルを置く
中身は以下

[build]
builder = "gcr.io/buildpacks/builder:google-22"

4 ソースからのデプロイ実行

ここまでで src 配下が以下のようになっている

/src/.python-version
/src/Procfile
/src/api/[main から使用されるプログラム群]
/src/main.py
/src/project.toml
/src/requierements.txt (書いておくと自動ビルド時に pip install される)

コマンドオプションの詳細はシステム要件によって異なると思うので
リファレンス を参考に

ソースからデプロイを実行する

gcloud run deploy [サービス名] \\
--source . \\
--no-traffic \\ ★ 2 度目以降にデプロイする場合、traffic 0% とするために付与
--cpu-throttling \\ CPU を使っているときだけ課金
--execution-environment gen1 \\ 小さいアプリなら第一世代 [世代について](https://cloud.google.com/run/docs/about-execution-environments?hl=ja)
--region [リージョン名] \\ ex) asia-northeast1
--ingress internal \\ ★ 内部からコールされるだけなら外部からのアクセスは遮断でよい
--no-allow-unauthenticated \\ サービスアカウントによるアクセスに限る。 allow- にすると認証しない
--service-account xxx \\
--min-instances 0 \\ ★リクエストのない時間帯はインスタンスが 0 になり課金されなくなる
--max-instances 1 \\ ★ 指定しないと無尽蔵に増えるので設定必須
--cpu XX \\
--memory XXG \\
--revision-suffix \\ XXXXXX
--tag \\ XXXXX
--timeout \\ nginx のタイムアウト

実行すると
Cloud Build により自動ビルドが行われ、Artifact Registory に自動でコンテナイメージが登録され、そのイメージを使ってアプリケーションのサービスがセットアップされる。ログは Cloud Build のページや Cloud logging の Buider ログで確認できる。

5 Artifact Registry に上がったコンテナイメージにデプロイしたものと同じタグを付与しておく

これをやっておかないとデプロイするほどどれがどのバージョンのイメージかわからなくなっていく

gcloud artifacts docker tags add \\
 [イメージ名(パス+サービス名]:latest \\
 [イメージ名(パス+サービス名]:[revision-suffix で指定したものと同じバージョン]

  ex) asia-northeast1-docker.pkg.dev/[myproject]/cloud-run-source-deploy/[myapp]

6 正常にデプロイされていることが確認できたら

Cloud Run ページの [リビジョン] タブでトラフィックを切り替えれば OK

参考

Cloud Run に提供されているランタイムのサポート期限
https://cloud.google.com/run/docs/runtime-support?hl=ja

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?