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 Editor
- 前往 Cloud Shell Editor
- 如果终端未显示在屏幕底部,请打开它:
- 点击汉堡式菜单
- 点击终端
- 点击 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
- 在 Cloud Shell Editor 中打开
server.ts
文件: 现在,屏幕顶部应该会显示一个文件。您可以在此处修改此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);
- 在 Cloud Shell Editor 中打开
angular.json
文件: 现在,我们将向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"]
- 在 Cloud Shell Editor 中打开
app.component.ts
文件: 现在,屏幕顶部应该会显示一个现有文件。您可以在此处修改此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
几分钟后,应用应会提供一个网址供您访问。
前往该网址,查看应用的实际运行情况。每次访问该网址或刷新页面时,您都会看到 Tasks 应用。
9. 恭喜
在本实验中,您学习了如何执行以下操作:
- 创建 Cloud SQL for PostgreSQL 实例
- 将应用部署到 Cloud Run,以连接到 Cloud SQL 数据库
清理
Cloud SQL 没有免费层级,如果您继续使用,我们会向您收费。您可以删除 Cloud 项目,以避免产生额外费用。
虽然 Cloud Run 不会对未在使用中的服务计费,但您可能仍然需要为将容器映像存储在 Artifact Registry 中而产生的相关费用付费。删除 Cloud 项目后,系统即会停止对该项目中使用的所有资源计费。
如有需要,请删除项目:
gcloud projects delete $GOOGLE_CLOUD_PROJECT
您可能还希望从 Cloud Shell 磁盘中删除不必要的资源。您可以:
- 删除 Codelab 项目目录:
rm -rf ~/task-app
- 警告!下一步操作无法撤消!如果您想删除 Cloud Shell 中的所有内容以释放空间,可以删除整个主目录。请务必将您要保留的所有内容保存到其他位置。
sudo rm -rf $HOME