🎉

Cloud Run+Cloud SQLでRails×Next.jsアプリをデプロイしてみた

に公開

個人開発で作るRails×Next.jsアプリをCloud Run+Cloud SQLの構成でデプロイしてみました。

最初はClaude Sonnet 4が作ってくれたPRをベースにデプロイしてみたのですが、一発では通らなかったのでハマったポイントをいくつかまとめてみました。

ベースにしたPRはこちら
https://github.com/okdyy75/opcha/pull/1

実際に使用したソースはこちら
https://github.com/okdyy75/opcha/tree/google_cloud_deploy

前提

  • ひとまずpublicネットワーク上に構築
  • Cloud SQLの最安インスタンスを使うために台湾リージョン(asia-east1)を使用

Cloud SQL

まずはインスタンスを作成していきます

gcloud sql instances create opcha-db \
  --database-version=POSTGRES_17 \
  --tier=db-f1-micro \
  --region=asia-east1

API [sqladmin.googleapis.com] not enabled on project [<PROJECT_ID>]. Would you like to enable and retry (this will take
 a few minutes)? (y/N)?  y

Enabling service [sqladmin.googleapis.com] on project [<PROJECT_ID>]...
Operation "operations/acat.p2-xxxxx-xxxxx-xxxxx-xxxxx-xxxxx-xxxxx" finished successfully.
ERROR: (gcloud.sql.instances.create) HTTPError 400: Invalid request: Invalid Tier (db-f1-micro) for (ENTERPRISE_PLUS) Edition. Use a predefined Tier like db-perf-optimized-N-* instead. Learn more at https://cloud.google.com/sql/docs/postgres/create-instance#machine-types.

作成しようとしたところ、db-f1-microインスタンスが無効な旨のエラーが発生。
どうやら--editionを指定しないとデフォルトでEnterprise Plusエディションになってしまうらしいので、明示的にEnterpriseエディションを指定します。
ついでにストレージやpostgreSQLのバージョンも指定しておきます。

gcloud sql instances create opcha-db \
  --edition=enterprise \
  --database-version=POSTGRES_17 \
  --storage-type=HDD  \
  --storage-size=10 \
  --tier=db-f1-micro \
  --region=asia-east1

Creating Cloud SQL instance for POSTGRES_17...done.                                                                   
Created [https://sqladmin.googleapis.com/sql/v1beta4/projects/<PROJECT_ID>/instances/opcha-db].
NAME        DATABASE_VERSION  LOCATION      TIER         PRIMARY_ADDRESS  PRIVATE_ADDRESS  STATUS
opcha-db    POSTGRES_17       asia-east1-c  db-f1-micro  35.236.180.149   -                RUNNABLE

次に作成したDBにローカルPCからアクセスしてみます

gcloud sql connect opcha-db --user=postgres

ERROR: (gcloud.sql.connect) HTTPError 400: Invalid request: Invalid flag for instance role: CloudSQL Second Generation doesn't support IPv6 networks/subnets: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx.

どうやらIPv6でのDB接続ができないようなのでPCのWiFiのIPv6の設定を「リンクローカルのみ」にします

MacでIPv6の設定をオフにする
https://gumfum.hatenablog.com/entry/2021/01/02/183000

再度DBに接続してみます

gcloud sql connect opcha-db --user=postgres

ERROR: (gcloud.sql.connect) Psql client not found.  Please install a psql client and make sure it is in PATH to be able to connect to the database instance.

今度はpsql clientが見つからないエラーが発生したのでbrewコマンドでpostgresqlをインストールします。(brew install postgresqlでインストールした場合、古いバージョンのpostgreが入るので明示的にバージョンを指定)

brew install postgresql@17

再度DBに接続してみます。(その2)

gcloud sql connect opcha-db --user=postgres

Allowlisting your IP for incoming connection for 5 minutes...done.                                                    
Connecting to database with SQL user [postgres].Password: 
psql: error: connection to server at "xxx.xxx.xxx.xxx", port 5432 failed: FATAL:  password authentication failed for user "postgres"
connection to server at "xxx.xxx.xxx.xxx", port 5432 failed: FATAL:  password authentication failed for user "postgres"

パスワードが設定されておらずログインできないようので設定していきます

デフォルトユーザーのパスワードを設定
https://cloud.google.com/sql/docs/postgres/users?hl=ja#default-users

gcloud sql users set-password postgres \
    --instance=opcha-db \
    --password=xxxxx

再度DBに接続してみます。(その3)

gcloud sql connect opcha-db --user=postgres

Allowlisting your IP for incoming connection for 5 minutes...done.                                                    
Connecting to database with SQL user [postgres].Password: 
psql (17.5 (Homebrew))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off, ALPN: postgresql)
Type "help" for help.

postgres=> 

接続に成功しました!

ローカルPCからCloud SQLに接続

次にSQLクライアントからも接続できるように設定します。

こちらの記事が非常に参考になりました

Cloud SQLのデータベースにローカルから接続する方法
https://qiita.com/ryu-yama/items/f635a7608469bf019de7

まずはサービスアカウントを作成してcredentialのjsonを取得します。
詳細はドキュメント通りなので割愛

サービス アカウントを設定する
https://cloud.google.com/sql/docs/postgres/connect-instance-local-computer?hl=ja#set_up_a_service_account

次にM1Mac用のCloud SQL Auth ProxyをDLします

Cloud SQL Auth Proxy を使用して接続する
https://cloud.google.com/sql/docs/mysql/connect-auth-proxy?hl=ja#mac-m1

自分は.google_cloudディレクトリを作成して、そこにcredentialのjsonとcloud-sql-proxyを配置。ポート1234でProxyを起動しました

./.google_cloud/cloud-sql-proxy \
  --credentials-file ./.google_cloud/opcha_key.json \
  --port 1234 \
  <PROJECT_ID>:asia-east1:opcha-db

Authorizing with the credentials file at "./.google_cloud/opcha_key.json"
[<PROJECT_ID>:asia-east1:opcha-db] Listening on 127.0.0.1:1234
The proxy has started successfully and is ready for new connections!

pgAdmin4から下記設定で無事接続できました

Host:localhost
Port:1234
ユーザー名:postgres
パスワード:xxxxx

Cloud Run

続いてCloud Runを動かしてみます。Claudeが作ってくれたcloudbuild.yamlを元に一部修正します。

Cloud RunでデプロイしているRailsアプリをCloud SQLに接続する方法を調べたところ、公式ドキュメントに記載があったのでこれを元に修正していきます(非常に参考になりました)

Running Rails on the Cloud Run environment
https://cloud.google.com/ruby/rails/run

cloudbuild.yaml

steps:
  # Build backend image
  - name: gcr.io/cloud-builders/docker
    args:
      - build
      - -t
      - gcr.io/$PROJECT_ID/opcha-backend:$COMMIT_SHA
      - -t
      - gcr.io/$PROJECT_ID/opcha-backend:latest
      - ./backend
    id: build-backend

  # Build frontend image
  - name: gcr.io/cloud-builders/docker
    args:
      - build
      - -t
      - gcr.io/$PROJECT_ID/opcha-frontend:$COMMIT_SHA
      - -t
      - gcr.io/$PROJECT_ID/opcha-frontend:latest
      - ./frontend
    id: build-frontend

  # Push backend image
  - name: gcr.io/cloud-builders/docker
    args:
      - push
      - gcr.io/$PROJECT_ID/opcha-backend:$COMMIT_SHA
    id: push-backend
    waitFor: [build-backend]

  # Push frontend image
  - name: gcr.io/cloud-builders/docker
    args:
      - push
      - gcr.io/$PROJECT_ID/opcha-frontend:$COMMIT_SHA
    id: push-frontend
    waitFor: [build-frontend]

  # Deploy backend to Cloud Run
  - name: gcr.io/google.com/cloudsdktool/cloud-sdk
    entrypoint: gcloud
    args:
      - run
      - deploy
      - opcha-backend
      - --image=gcr.io/$PROJECT_ID/opcha-backend:$COMMIT_SHA
      - --region=$_REGION
      - --cpu=0.25 
      - --memory=0.5Gi 
      - --min-instances=0 
      - --allow-unauthenticated
      - --add-cloudsql-instances=$_CLOUDSQL_INSTANCE
      - --set-env-vars=RAILS_ENV=$_ENVIRONMENT
      - --set-env-vars=CLOUD_SQL_CONNECTION_NAME=$_CLOUDSQL_INSTANCE
      - --set-secrets="RAILS_MASTER_KEY=RAILS_MASTER_KEY:latest"
      - --set-secrets="DB_NAME=DB_NAME:latest"
      - --set-secrets="DB_USERNAME=DB_USERNAME:latest"
      - --set-secrets="DB_PASSWORD=DB_PASSWORD:latest"
      
    id: deploy-backend
    waitFor: [push-backend]

  # Deploy frontend to Cloud Run
  - name: gcr.io/google.com/cloudsdktool/cloud-sdk
    entrypoint: gcloud
    args:
      - run
      - deploy
      - opcha-frontend
      - --image=gcr.io/$PROJECT_ID/opcha-frontend:$COMMIT_SHA
      - --region=$_REGION
      - --cpu=0.25 
      - --memory=0.5Gi 
      - --min-instances=0 
      - --allow-unauthenticated
      - --set-env-vars=NODE_ENV=$_ENVIRONMENT
      - --set-env-vars=NEXT_PUBLIC_API_URL=$_API_URL
    id: deploy-frontend
    waitFor: [push-frontend]

substitutions:
  _REGION: asia-east1 # 台湾リージョン
  _ENVIRONMENT: production
  _CLOUDSQL_INSTANCE: ${PROJECT_ID}:${_REGION}:opcha-db
  _API_URL: http://localhost:3001
  _TAG: latest

options:
  logging: CLOUD_LOGGING_ONLY

合わせて環境変数をSecret Manegarに登録します。下記コマンドで環境変数を設定

# secret作成
echo -n 'xxxxx' | gcloud secrets create RAILS_MASTER_KEY --data-file=-

# secret更新
echo -n 'xxxxx' | gcloud secrets versions add RAILS_MASTER_KEY --data-file=-

Cloud Build実行

とりあえずデプロイしてみます

gcloud builds submit --config cloudbuild.yaml

Already have image (with digest): gcr.io/cloud-builders/docker
invalid argument "gcr.io/<PROJECT_ID>/opcha-backend:" for "-t, --tag" flag: invalid reference format
See 'docker build --help'.

早速エラー。ビルド実行の詳細ログを見てみると$COMMIT_SHAが空になっておりエラーになっていました。

build -t gcr.io/<PROJECT_ID>/opcha-backend: -t gcr.io/<PROJECT_ID>/opcha-backend:latest ./backend

どうやら$COMMIT_SHAはトリガービルド時に使用できる定義済み変数のようで、ひとまず今回は削除してlatestタグのみ使用します

変数値の置換
https://cloud.google.com/build/docs/configuring-builds/substitute-variable-values?hl=ja

再度実行してみます

Deploying container to Cloud Run service [opcha-backend] in project [<PROJECT_ID>] region [asia-east1]
Deploying new service...
failed
Deployment failed
ERROR: (gcloud.run.deploy) service.spec.template.spec.containers[0].env[2].value_from.secret_key_ref.key: should have only alphanumeric characters, hyphens, and underscores, or positive integers

再度エラー。どうやら環境変数の指定方法が間違っており、--set-secrets="RAILS_MASTER_KEY=RAILS_MASTER_KEY:latest"ではなく、正しくは--set-secrets=RAILS_MASTER_KEY=RAILS_MASTER_KEY:latestでダブルクォーテーションで囲む必要は無かったようです。

再度実行してみます(その2)

gcr.io/google.com/cloudsdktool/cloud-sdk:latest
Deploying container to Cloud Run service [opcha-backend] in project [<PROJECT_ID>] region [asia-east1]
Deploying new service...
failed
Deployment failed
ERROR: (gcloud.run.deploy) spec.template.metadata.annotations: Invalid cloud sql instance names: ['${PROJECT_ID}:${_REGION}:opcha-db']. Instance names must be 97 characters or less, matching [a-zA-Z0-9-]{1,}:[a-zA-Z0-9-]{1,}:[a-z][a-z0-9-]{0,}, and cannot end in an hyphen

またしてもエラー。どうやらsubstitutions内に定義した_CLOUDSQL_INSTANCE: ${PROJECT_ID}:${_REGION}:opcha-dbがうまく置換できておらずエラーになっていました。substitutions内で変数展開する場合はdynamicSubstitutions: trueを設定してbashパラメータの拡張を有効にする必要があるようです。

再度実行してみます(その3)

ERROR: (gcloud.run.deploy) Revision 'opcha-backend-00001-8h6' is not ready and cannot serve traffic. spec.template.spec.containers[0].env[2].value_from.secret_key_ref.name: Permission denied on secret: projects/<PROJECT_NUMBER>/secrets/RAILS_MASTER_KEY/versions/latest for Revision service account <PROJECT_NUMBER>-compute@developer.gserviceaccount.com. The service account used must be granted the 'Secret Manager Secret Accessor' role (roles/secretmanager.secretAccessor) at the secret, project or higher level.
spec.template.spec.containers[0].env[3].value_from.secret_key_ref.name: Permission denied on secret: projects/<PROJECT_NUMBER>/secrets/DB_NAME/versions/latest for Revision service account <PROJECT_NUMBER>-compute@developer.gserviceaccount.com. The service account used must be granted the 'Secret Manager Secret Accessor' role (roles/secretmanager.secretAccessor) at the secret, project or higher level.

今度はSecret Managerへのアクセス権限が無いとのエラー

どうやらCloud Runのサービスアカウントである<PROJECT_NUMBER>-compute@developer.gserviceaccount.comへSecret Managerへのアクセス権限が必要なので付与していきます。

gcloud projects add-iam-policy-binding <PROJECT_ID> \
    --member="serviceAccount:<PROJECT_NUMBER>-compute@developer.gserviceaccount.com" \
    --role="roles/secretmanager.secretAccessor"

cloudbuildを通してのデプロイはfrontend側は成功したので、一旦ここでgcloudを使ってbackendのみデプロイできるか試してみます

gcloud run deploy opcha-backend \
    --image=gcr.io/<PROJECT_ID>/opcha-backend:latest \
    --region=asia-east1 \
    --allow-unauthenticated \
    --add-cloudsql-instances=<PROJECT_ID>:asia-east1:opcha-db \
    --cpu=0.25 \
    --memory=0.5Gi \
    --min-instances=0 \
    --set-env-vars=RAILS_ENV=production \
    --set-env-vars=CLOUD_SQL_CONNECTION_NAME=<PROJECT_ID>:asia-east1:opcha-db \
    --set-secrets=RAILS_MASTER_KEY=RAILS_MASTER_KEY:latest \
    --set-secrets=DB_NAME=DB_NAME:latest \
    --set-secrets=DB_USERNAME=DB_USERNAME:latest \
    --set-secrets=DB_PASSWORD=DB_PASSWORD:latest

エラーになったので再度内容を確認してみると、環境変数のPORT=8080で定義したポートを起動およびリッスンできませんでした。といった旨のエラーが発生。

Ready condition status changed to False for Revision opcha-backend-00002-82v with message: 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.

どうやらCloud Runではデフォルトで8080ポートをリッスンするようなので、Cloud Runデプロイ時にポート番号を指定する必要があるようです

コンテナポートを構成する
https://cloud.google.com/run/docs/configuring/services/containers?hl=ja#configure-port

一部Railsアプリ内のエラー等ありましたが、ひとまずbackendとfrontendのデプロイに成功!!

gcloud builds submit --config cloudbuild.yaml

Creating temporary archive of 19368 file(s) totalling 383.8 MiB before compression.
Some files were not included in the source upload.

Waiting for build to complete. Polling interval: 1 second(s).
ID                                    CREATE_TIME                DURATION  SOURCE       IMAGES  STATUS
xxxxx-xxxxx-xxxxx-xxxxx-xxxxx  2025-06-19T04:44:27+00:00  8M20S     gs://<PROJECT_ID>_cloudbuild/source/xxxxx.xxxxx-xxxxx.tgz  -       SUCCESS
Deploying container to Cloud Run service [opcha-backend] in project [<PROJECT_ID>] region [asia-east1]
Deploying...
Setting IAM Policy................................warning
Creating Revision...........................................................................................................................................................................................................................................................................................................done
Routing traffic.....done
Completed with warnings:
  Setting IAM policy failed, try "gcloud beta run services add-iam-policy-binding --region=asia-east1 --member=allUsers --role=roles/run.invoker opcha-backend"
Service [opcha-backend] revision [opcha-backend-00007-6b8] has been deployed and is serving 100 percent of traffic.
Service URL: https://opcha-backend-<PROJECT_NUMBER>.asia-east1.run.app

Deploying container to Cloud Run service [opcha-frontend] in project [<PROJECT_ID>] region [asia-east1]
Deploying...
Setting IAM Policy................................warning
Creating Revision..............................................................................................done
Routing traffic.....done
Completed with warnings:
  Setting IAM policy failed, try "gcloud beta run services add-iam-policy-binding --region=asia-east1 --member=allUsers --role=roles/run.invoker opcha-frontend"
Service [opcha-frontend] revision [opcha-frontend-00002-lpp] has been deployed and is serving 100 percent of traffic.
Service URL: https://opcha-frontend-<PROJECT_NUMBER>.asia-east1.run.app

ハマりポイント

  • バックエンドのgcloud run deploy時に--port=80を指定してデプロイするが、ログを見ると「Listening on http://0.0.0.0:3000」になってしまうのでPumaのデフォルトポートである--port=3000を指定すると起動できた。--port=80を指定すれば環境変数の$PORTもセットされると思ったが、うまく動かなかった原因は分からず・・
  • デプロイ後はフロントエンドにアクセス出来なかったが、Google Cloud管理画面から「Cloud Run > サービス > frontend > セキュリティ > Allow unauthenticated invocations」を有効にするとアクセスできるようになった。cloudbuild.yamlで--allow-unauthenticatedを指定していたのに有効になっていなかった原因は分からず・・
  • iamの権限を全て表示するには「Google提供のロール付与を含める」のチェックをONにする

IAM表示

バックエンドとフロントエンドの疎通確認

backendとfrontendとの疎通確認用にapiと画面を作っておきます

backend/app/controllers/api/hello_controller.rb

require "socket"

class Api::HelloController < ApplicationController
  def hello
    hostname = Socket.gethostname
    current_time = Time.now.in_time_zone("Asia/Tokyo")

    render json: {
      message: "Hello World",
      version: Rails.version,
      hostname: hostname,
      current_time: current_time
    }
  end
end

frontend/src/app/hello/page.tsx

interface ApiResponse {
  message: string;
  version: string;
  hostname: string;
  current_time: string;
}

async function fetchHelloData(): Promise<ApiResponse> {
  try {
    // NEXT_PUBLIC_API_URL環境変数を使用
    const baseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://backend:80';
    const apiUrl = `${baseUrl}/api/hello`;
    
    console.log(apiUrl);
    const response = await fetch(apiUrl, {
      cache: 'no-store', // 常に最新のデータを取得
      headers: {
        'Content-Type': 'application/json',
      },
    });
    console.log(response);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('Failed to fetch hello data:', error);
    throw error;
  }
}

export default async function HelloPage() {
  let data: ApiResponse | null = null;
  let error: string | null = null;

  try {
    data = await fetchHelloData();
    console.log(data);
  } catch (err) {
    error = err instanceof Error ? err.message : 'An error occurred';
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-red-600 mb-4">エラーが発生しました</h1>
          <p className="text-gray-600">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md mx-auto bg-white rounded-lg shadow-md p-6">
        <h1 className="text-3xl font-bold text-center text-gray-900 mb-8">Hello Page</h1>
        
        {data && (
          <div className="p-8">
            <div className="space-y-2">
              <p><strong>メッセージ:</strong> {data.message}</p>
              <p><strong>Railsバージョン:</strong> {data.version}</p>
              <p><strong>ホスト名:</strong> {data.hostname}</p>
              <p><strong>現在時刻:</strong> {data.current_time}</p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
} 

バックエンド表示
フロントエンド表示

無事バックエンドとフロントエンドの疎通確認が取れたので次にDBとの疎通確認をします

DBとの疎通確認

とりあえずモデルとコントローラを作成して

# モデル作成
bin/rails g model MovieGenre name:string

# コントローラー作成
bin/rails g scaffold_controller api/MovieGenre --api

seedを設定しておきます

backend/db/seeds.rb

# This file should ensure the existence of records required to run the application in every environment (production,
# development, test). The code here should be idempotent so that it can be executed at any point in every environment.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Example:
#
  ["Action", "Comedy", "Drama", "Horror"].each do |genre_name|
    MovieGenre.find_or_create_by!(name: genre_name)
  end

seedをRailsコンテナから実行するためにジョブを作成&実行します

# ジョブの作成
gcloud run jobs create opcha-job \
    --image gcr.io/<PROJECT_ID>/opcha-backend:latest \
    --region=asia-east1 \
    --set-cloudsql-instances=<PROJECT_ID>:asia-east1:opcha-db \
    --set-env-vars=RAILS_ENV=production \
    --set-env-vars=DB_HOST='/cloudsql/<PROJECT_ID>:asia-east1:opcha-db' \
    --set-env-vars=DB_PORT=5432 \
    --set-secrets=RAILS_MASTER_KEY=RAILS_MASTER_KEY:latest \
    --set-secrets=DB_NAME=DB_NAME:latest \
    --set-secrets=DB_USERNAME=DB_USERNAME:latest \
    --set-secrets=DB_PASSWORD=DB_PASSWORD:latest

# ジョブの実行
gcloud run jobs execute opcha-job \
    --region=asia-east1 \
    --args=bin/rails,db:seed

DBのシードデータ表示

無事DBとの疎通確認も取れました

Artifact Registry設定

ただ今回使用しているgcr.ioドメインは廃止予定のコンテナレジストリなのでArtifact Registryに変更していきます

Repositoryを作成します

gcloud artifacts repositories create opcha-repo \ 
    --repository-format=docker \
    --location=asia-east1 \
    --project=<PROJECT_ID>

cloudbuild.yamlを修正

# before
- gcr.io/$PROJECT_ID/opcha-backend:latest

# after  
- asia-east1-docker.pkg.dev/$PROJECT_ID/opcha-repo/opcha-backend:latest

Artifact Registryへのアクセス権限はCloud Buildにデフォルトであるようです

Google Cloud デフォルトの権限 - Artifact Registry IAM によるアクセス制御
https://cloud.google.com/artifact-registry/docs/access-control?hl=ja#gcp

完成系

最終的に出来上がったcloudbuild.yamlはこちら

steps:
  # Build backend image
  - name: gcr.io/cloud-builders/docker
    args:
      - build
      - -t
      - asia-east1-docker.pkg.dev/${PROJECT_ID}/opcha-repo/opcha-backend:latest
      - ./backend
    id: build-backend

  # Build frontend image
  - name: gcr.io/cloud-builders/docker
    args:
      - build
      - -t
      - asia-east1-docker.pkg.dev/${PROJECT_ID}/opcha-repo/opcha-frontend:latest
      - ./frontend
    id: build-frontend

  # Push backend image
  - name: gcr.io/cloud-builders/docker
    args:
      - push
      - asia-east1-docker.pkg.dev/${PROJECT_ID}/opcha-repo/opcha-backend:latest
    id: push-backend
    waitFor: [build-backend]

  # Push frontend image
  - name: gcr.io/cloud-builders/docker
    args:
      - push
      - asia-east1-docker.pkg.dev/${PROJECT_ID}/opcha-repo/opcha-frontend:latest
    id: push-frontend
    waitFor: [build-frontend]

  # Deploy backend to Cloud Run
  - name: gcr.io/google.com/cloudsdktool/cloud-sdk
    entrypoint: gcloud
    args:
      - run
      - deploy
      - opcha-backend
      - --image=asia-east1-docker.pkg.dev/${PROJECT_ID}/opcha-repo/opcha-backend:latest
      - --region=$_REGION
      - --allow-unauthenticated
      - --add-cloudsql-instances=${_CLOUDSQL_INSTANCE}
      - --cpu=0.25
      - --memory=0.5Gi
      - --min-instances=0
      - --port=3000
      - --set-env-vars=RAILS_ENV=${_ENVIRONMENT}
      - --set-env-vars=DB_HOST=/cloudsql/${_CLOUDSQL_INSTANCE}
      - --set-env-vars=DB_PORT=5432
      - --set-secrets=RAILS_MASTER_KEY=RAILS_MASTER_KEY:latest
      - --set-secrets=DB_NAME=DB_NAME:latest
      - --set-secrets=DB_USERNAME=DB_USERNAME:latest
      - --set-secrets=DB_PASSWORD=DB_PASSWORD:latest
    id: deploy-backend
    waitFor: [push-backend]

  # Deploy frontend to Cloud Run
  - name: gcr.io/google.com/cloudsdktool/cloud-sdk
    entrypoint: gcloud
    args:
      - run
      - deploy
      - opcha-frontend
      - --image=asia-east1-docker.pkg.dev/${PROJECT_ID}/opcha-repo/opcha-frontend:latest
      - --region=$_REGION
      - --allow-unauthenticated
      - --cpu=0.25
      - --memory=0.5Gi
      - --min-instances=0
      - --port=3000
      - --set-env-vars=NODE_ENV=${_ENVIRONMENT}
      - --set-env-vars=NEXT_PUBLIC_API_URL=${_API_URL}
    id: deploy-frontend
    waitFor: [push-frontend]

substitutions:
  _REGION: asia-east1 # 台湾リージョン
  _ENVIRONMENT: production
  _CLOUDSQL_INSTANCE: ${PROJECT_ID}:${_REGION}:opcha-db
  _API_URL: https://opcha-backend-33r64w4piq-de.a.run.app

options:
  logging: CLOUD_LOGGING_ONLY
  dynamicSubstitutions: true

触ってみてのポイント

  • 構成ファイルを通してのビルド(gcloud builds submit --config cloudbuild.yaml)は簡単なRailsアプリでも10分〜と時間がかかるので、まずは手元で一度直接gcloud builds submitなりgcloud run deployして動作を確認した方が早い
  • Cloud Runの「リクエストベースでの起動(最小インスタンス0)」はやはりURLを叩いてからインスタンスの起動まで簡単なRailsアプリでも10秒ほどかかるので意識しておきたい
  • CPU 0.25、メモリ0.5GiBでもとりあえず簡単なRailsアプリを動かすことができた

参考リンク

Discussion