👏

GCPでインフラ構築した際に発生したエラー

に公開

発生したエラー内容と解決法

1.エラー内容:Dockerイメージのプラットフォームが非対応

CloudRunでサービス作成時に起きた

Cloud Run does not support image 'asia-northeast1-docker.pkg.dev/stg-gearon/backend/image@sha256:99f258be38987eead84490425fed7a41fb5327d1a5b77bb32bba5d97225fabe5': Container manifest type 'application/vnd.oci.image.index.v1+json' must support amd64/linux.

M4 MAC(Apple Silicon)ではarm64向けのイメージが作られてしまう
Cloud Run が対応する amd64 用のイメージを作るために次のコマンドを実行

docker buildx build --platform=linux/amd64 -t asia-northeast1-docker.pkg.dev/stg-gearon/backend/image:tag --push .

(buildしてpushも同時に行える)

参照先
https://cloud.google.com/kubernetes-engine/docs/how-to/build-multi-arch-for-arm?hl=ja#build-the-image

2.エラー内容:コンテナ起動エラー

これもCloudRunでサービス作成時に起きた

失敗。詳細: Revision 'gearon-backend-00001-56q' is not ready and cannot serve traffic. The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable within the allocated timeout. This can happen when the container port is misconfigured or if the timeout is too short. The health check timeout can be extended. Logs for this revision might contain more information. Logs URL: Cloud Logging を開く For more troubleshooting guidance, see https://cloud.google.com/run/docs/troubleshooting#container-failed-to-start

原因:アプリが違うポートでリッスンしている

解決法①:ポート番号を揃える
アプリのコード内のポート番号を変更する、もしくはCloudRunのサービス作成時のポート番号を変更する。

解決法②:アプリ内のコードを変更する
元のコード

const port = 3000;

CloudRunではPORT8080、アプリではPORT3000に設定されていてアプリが違うポートでリッスンしているから起動できなかった。

変更後のコード

const port = process.env.PORT || 8080;

このコードは 「環境変数 PORT から値を取得して port という定数に代入する」 という処理をしてくれる。
Cloud Run では PORT 環境変数は自動で 8080 に設定されるので自分で設定する必要はない。

参照先
https://cloud.google.com/migrate/containers/docs/deploy-run?hl=ja#example_deploying_the_quickstart_container_on

Discussion