Google Cloud Run
Google Cloud Run 是由 Google Cloud 构建的无服务器平台。您可以响应事件运行代码,Google 会自动为您管理底层计算资源。
Google Cloud Run 使用容器来运行您的服务。这意味着您可以通过提供 Dockerfile 来使用任何您喜欢的运行时(例如,Deno 或 Bun)。如果未提供 Dockerfile,Google Cloud Run 将使用默认的 Node.js 构建包。
本指南假设您已经拥有 Google Cloud 账户和结算账户。
1. 安装 CLI
在使用 Google Cloud Platform 时,使用 gcloud CLI 是最简单的。
例如,在 MacOS 上使用 Homebrew:
sh
brew install --cask gcloud-cli使用 CLI 进行身份验证。
sh
gcloud auth login2. 项目设置
创建一个项目。在提示符处接受自动生成的项目 ID。
sh
gcloud projects create --set-as-default --name="my app"为您的项目 ID 和项目编号创建环境变量以便于重用。项目通过 gcloud projects list 命令成功返回可能需要 ~30 秒。
sh
PROJECT_ID=$(gcloud projects list \
--format='value(projectId)' \
--filter='name="my app"')
PROJECT_NUMBER=$(gcloud projects list \
--format='value(projectNumber)' \
--filter='name="my app"')
echo $PROJECT_ID $PROJECT_NUMBER查找您的结算账户 ID。
sh
gcloud billing accounts list将上一条命令中的结算账户添加到项目。
sh
gcloud billing projects link $PROJECT_ID \
--billing-account=[billing_account_id]启用所需的 API。
sh
gcloud services enable run.googleapis.com \
cloudbuild.googleapis.com更新服务账户权限以访问 Cloud Build。
sh
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member=serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com \
--role=roles/run.builder3. Hello World
使用 "create-hono" 命令启动您的项目。选择 nodejs。
sh
npm create hono@latest my-app进入 my-app 并安装依赖项。
sh
cd my-app
npm i将 src/index.ts 中的端口更新为 8080。
ts
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => {
return c.text('Hello Hono!')
})
serve({
fetch: app.fetch,
port: 3000
port: 8080
}, (info) => {
console.log(`Server is running on http://localhost:${info.port}`)
})在本地运行开发服务器。然后,在您的 Web 浏览器中访问 http://localhost:8080。
sh
npm run dev4. 部署
开始部署并按照交互式提示操作(例如,选择一个区域)。
sh
gcloud run deploy my-app --source . --allow-unauthenticated更改运行时
如果您想使用 Deno 或 Bun 运行时(或自定义的 Nodejs 容器)进行部署,请添加一个包含所需环境的 Dockerfile(以及可选的 .dockerignore)。
有关容器化的信息,请参阅: