1. 概要
Cloud Run は、フルマネージド プラットフォームで、Google のスケーラブルなインフラストラクチャ上で直接コードを実行できます。この Codelab では、Node.js Admin SDK を使用して、Cloud Run の Angular アプリケーションを Firestore データベースに接続する方法について説明します。
このラボでは、次の方法について学びます。
- Firestore データベースを作成する
- Firestore データベースに接続するアプリケーションを Cloud Run にデプロイする
2. 前提条件
- Google アカウントをお持ちでない場合は、Google アカウントを作成する必要があります。
- 仕事用または学校用のアカウントではなく、個人アカウントを使用している。職場用アカウントや学校用アカウントには、このラボに必要な API を有効にできない制限が適用されている場合があります。
3. プロジェクトの設定
- Google Cloud コンソールにログインします。
- Cloud コンソールで課金を有効にする。
- このラボを完了しても、Cloud リソースの費用は 1 米ドル未満です。
- このラボの最後にある手順に沿ってリソースを削除すると、それ以上の請求が発生しなくなります。
- 新規ユーザーは、300 米ドル分の無料トライアルをご利用いただけます。
- 新しいプロジェクトを作成するか、既存のプロジェクトを再利用するかを選択します。
4. Cloud Shell エディタを開く
- Cloud Shell エディタに移動します。
- ターミナルが画面の下部に表示されない場合は、開きます。
- ハンバーガー メニュー
をクリックします。
- [Terminal] をクリックします。
- [New Terminal] をクリックします。
- ハンバーガー メニュー
- ターミナルで、次のコマンドを使用してプロジェクトを設定します。
- 形式:
gcloud config set project [PROJECT_ID]
- 例:
gcloud config set project lab-project-id-example
- プロジェクト ID がわからない場合:
- すべてのプロジェクト ID を一覧表示するには、次のコマンドを使用します。
gcloud projects list | awk '/PROJECT_ID/{print $2}'
- すべてのプロジェクト ID を一覧表示するには、次のコマンドを使用します。
- 形式:
- 承認を求められたら、[承認] をクリックして続行します。
- 次のようなメッセージが表示されます。
Updated property [core/project].
WARNING
が表示され、Do you want to continue (Y/N)?
を求められた場合は、プロジェクト ID が正しく入力されていない可能性があります。N
キー、Enter
キーを押して、gcloud config set project
コマンドをもう一度実行してみてください。
5. API を有効にする
ターミナルで、API を有効にします。
gcloud services enable \
firestore.googleapis.com \
run.googleapis.com \
artifactregistry.googleapis.com \
cloudbuild.googleapis.com
承認を求められたら、[承認] をクリックして続行します。
このコマンドが完了するまで数分かかる場合がありますが、最終的には次のような成功メッセージが表示されます。
Operation "operations/acf.p2-73d90d00-47ee-447a-b600" finished successfully.
6. Firestore データベースを作成する
gcloud firestore databases create
コマンドを実行して Firestore データベースを作成します。gcloud firestore databases create --location=nam5
7. 申請書類を準備する
HTTP リクエストに応答する Next.js アプリケーションを準備します。
task-app
という名前の新しい Next.js プロジェクトを作成するには、次のコマンドを使用します。npx --yes @angular/cli@19.2.5 new task-app \ --minimal \ --inline-template \ --inline-style \ --ssr \ --server-routing \ --defaults
- ディレクトリを
task-app
に変更します。cd task-app
firebase-admin
をインストールして、Firestore データベースを操作します。npm install firebase-admin
server.ts
ファイルを Cloud Shell エディタで開きます。 画面上部にファイルが表示されます。このcloudshell edit src/server.ts
server.ts
ファイルを編集できます。server.ts
ファイルの既存の内容を削除します。- 次のコードをコピーして、開いた
server.ts
ファイルに貼り付けます。import { AngularNodeAppEngine, createNodeRequestHandler, isMainModule, writeResponseToNodeResponse, } from '@angular/ssr/node'; import express from 'express'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { initializeApp, applicationDefault, getApps } from 'firebase-admin/app'; import { getFirestore } from 'firebase-admin/firestore'; type Task = { id: string; title: string; status: 'IN_PROGRESS' | 'COMPLETE'; createdAt: number; }; const credential = applicationDefault(); // Only initialize app if it does not already exist if (getApps().length === 0) { initializeApp({ credential }); } const db = getFirestore(); const tasksRef = db.collection('tasks'); const serverDistFolder = dirname(fileURLToPath(import.meta.url)); const browserDistFolder = resolve(serverDistFolder, '../browser'); const app = express(); const angularApp = new AngularNodeAppEngine(); app.use(express.json()); app.get('/api/tasks', async (req, res) => { const snapshot = await tasksRef.orderBy('createdAt', 'desc').limit(100).get(); const tasks: Task[] = snapshot.docs.map(doc => ({ id: doc.id, title: doc.data()['title'], status: doc.data()['status'], createdAt: doc.data()['createdAt'], })); res.send(tasks); }); app.post('/api/tasks', async (req, res) => { const newTaskTitle = req.body.title; if(!newTaskTitle){ res.status(400).send("Title is required"); return; } await tasksRef.doc().create({ title: newTaskTitle, status: 'IN_PROGRESS', createdAt: Date.now(), }); res.sendStatus(200); }); app.put('/api/tasks', async (req, res) => { const task: Task = req.body; if (!task || !task.id || !task.title || !task.status) { res.status(400).send("Invalid task data"); return; } await tasksRef.doc(task.id).set(task); res.sendStatus(200); }); app.delete('/api/tasks', async (req, res) => { const task: Task = req.body; if(!task || !task.id){ res.status(400).send("Task ID is required"); return; } await tasksRef.doc(task.id).delete(); res.sendStatus(200); }); /** * Serve static files from /browser */ app.use( express.static(browserDistFolder, { maxAge: '1y', index: false, redirect: false, }), ); /** * Handle all other requests by rendering the Angular application. */ app.use('/**', (req, res, next) => { angularApp .handle(req) .then((response) => response ? writeResponseToNodeResponse(response, res) : next(), ) .catch(next); }); /** * Start the server if this module is the main entry point. * The server listens on the port defined by the `PORT` environment variable, or defaults to 4000. */ if (isMainModule(import.meta.url)) { const port = process.env['PORT'] || 4000; app.listen(port, () => { console.log(`Node Express server listening on http://localhost:${port}`); }); } /** * Request handler used by the Angular CLI (for dev-server and during build) or Firebase Cloud Functions. */ export const reqHandler = createNodeRequestHandler(app);
angular.json
ファイルを Cloud Shell エディタで開きます。cloudshell edit angular.json
angular.json
ファイルに"externalDependencies": ["firebase-admin"]
行を追加します。angular.json
ファイルの既存の内容を削除します。- 次のコードをコピーして、開いた
angular.json
ファイルに貼り付けます。{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "task-app": { "projectType": "application", "schematics": { "@schematics/angular:component": { "inlineTemplate": true, "inlineStyle": true, "skipTests": true }, "@schematics/angular:class": { "skipTests": true }, "@schematics/angular:directive": { "skipTests": true }, "@schematics/angular:guard": { "skipTests": true }, "@schematics/angular:interceptor": { "skipTests": true }, "@schematics/angular:pipe": { "skipTests": true }, "@schematics/angular:resolver": { "skipTests": true }, "@schematics/angular:service": { "skipTests": true } }, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/task-app", "index": "src/index.html", "browser": "src/main.ts", "polyfills": [ "zone.js" ], "tsConfig": "tsconfig.app.json", "assets": [ { "glob": "**/*", "input": "public" } ], "styles": [ "src/styles.css" ], "scripts": [], "server": "src/main.server.ts", "outputMode": "server", "ssr": { "entry": "src/server.ts" }, "externalDependencies": ["firebase-admin"] }, "configurations": { "production": { "budgets": [ { "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" }, { "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" } ], "outputHashing": "all" }, "development": { "optimization": false, "extractLicenses": false, "sourceMap": true } }, "defaultConfiguration": "production" }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "configurations": { "production": { "buildTarget": "task-app:build:production" }, "development": { "buildTarget": "task-app:build:development" } }, "defaultConfiguration": "development" }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n" } } } } }
"externalDependencies": ["firebase-admin"]
app.component.ts
ファイルを Cloud Shell エディタで開きます。 画面上部に既存のファイルが表示されます。このcloudshell edit src/app/app.component.ts
app.component.ts
ファイルを編集できます。app.component.ts
ファイルの既存の内容を削除します。- 次のコードをコピーして、開いた
app.component.ts
ファイルに貼り付けます。import { afterNextRender, Component, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; type Task = { id: string; title: string; status: 'IN_PROGRESS' | 'COMPLETE'; createdAt: number; }; @Component({ selector: 'app-root', standalone: true, imports: [FormsModule], template: ` <section> <input type="text" placeholder="New Task Title" [(ngModel)]="newTaskTitle" class="text-black border-2 p-2 m-2 rounded" /> <button (click)="addTask()">Add new task</button> <table> <tbody> @for (task of tasks(); track task) { @let isComplete = task.status === 'COMPLETE'; <tr> <td> <input (click)="updateTask(task, { status: isComplete ? 'IN_PROGRESS' : 'COMPLETE' })" type="checkbox" [checked]="isComplete" /> </td> <td>{{ task.title }}</td> <td>{{ task.status }}</td> <td> <button (click)="deleteTask(task)">Delete</button> </td> </tr> } </tbody> </table> </section> `, styles: '', }) export class AppComponent { newTaskTitle = ''; tasks = signal<Task[]>([]); constructor() { afterNextRender({ earlyRead: () => this.getTasks() }); } async getTasks() { const response = await fetch(`/api/tasks`); const tasks = await response.json(); this.tasks.set(tasks); } async addTask() { await fetch(`/api/tasks`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: this.newTaskTitle, status: 'IN_PROGRESS', createdAt: Date.now(), }), }); this.newTaskTitle = ''; await this.getTasks(); } async updateTask(task: Task, newTaskValues: Partial<Task>) { await fetch(`/api/tasks`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...task, ...newTaskValues }), }); await this.getTasks(); } async deleteTask(task: any) { await fetch('/api/tasks', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(task), }); await this.getTasks(); } }
これで、アプリケーションをデプロイする準備が整いました。
8. アプリケーションを Cloud Run にデプロイする
- 次のコマンドを実行して、アプリケーションを Cloud Run にデプロイします。
gcloud run deploy helloworld \ --region=us-central1 \ --source=.
- メッセージが表示されたら、
Y
とEnter
を押して続行することを確認します。Do you want to continue (Y/n)? Y
数分後、アクセスする URL がアプリケーションに表示されます。
URL に移動して、アプリケーションの動作を確認します。URL にアクセスするたび、またはページを更新するたびに、タスクアプリが表示されます。
9. 完了
このラボでは、以下の操作について学習しました。
- Cloud SQL for PostgreSQL インスタンスを作成する
- Cloud SQL データベースに接続するアプリケーションを Cloud Run にデプロイする
クリーンアップ
Cloud SQL には無料枠がないため、引き続き使用すると料金が発生します。Cloud プロジェクトを削除して、追加料金が発生しないようにすることができます。
サービスが使用されていない場合、Cloud Run の料金は発生しませんが、コンテナ イメージを Artifact Registry に保存すると課金される場合があります。Cloud プロジェクトを削除すると、そのプロジェクト内で使用されているすべてのリソースに対する課金が停止します。
必要に応じて、プロジェクトを削除します。
gcloud projects delete $GOOGLE_CLOUD_PROJECT
cloudshell ディスクから不要なリソースを削除することもできます。次のことが可能です。
- Codelab プロジェクト ディレクトリを削除します。
rm -rf ~/task-app
- 警告: 次の操作は元に戻せません。Cloud Shell 上のすべてのファイルを削除して空き容量を確保する場合は、ホーム ディレクトリ全体を削除できます。残しておきたいものはすべて別の場所に保存してください。
sudo rm -rf $HOME
学習を継続
- Cloud SQL Node.js コネクタを使用して、Cloud SQL for PostgreSQL でフルスタック Next.js アプリケーションを Cloud Run にデプロイする
- Cloud SQL Node.js コネクタを使用して、Cloud SQL for PostgreSQL でフルスタック Angular アプリケーションを Cloud Run にデプロイする
- Node.js Admin SDK を使用して、Firestore でフルスタック Angular アプリケーションを Cloud Run にデプロイする
- Node.js Admin SDK を使用して、Firestore でフルスタックの Next.js アプリケーションを Cloud Run にデプロイする