GCP Cloud Run:托管无服务器容器平台

FreeGuideOnline 最新 2026-07-01

bash gcloud services enable run.googleapis.com

3. 设置默认区域和项目 ID:
```bash
gcloud config set project YOUR_PROJECT_ID
gcloud config set run/region us-central1

准备示例应用

容器镜像需要包含一个监听 PORT 环境变量的 HTTP 服务器。我们先构建一个简单的 Node.js 应用。创建文件 index.js

const express = require('express');
const app = express();
const port = process.env.PORT || 8080;

app.get('/', (req, res) => {
  res.send('Hello from Cloud Run!');
});

app.listen(port, () => {
  console.log(`App listening on port ${port}`);
});

添加 package.json

{
  "name": "hello-cloud-run",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "express": "^4.18.2"
  }
}

然后构建容器镜像(确保在应用根目录下):

docker build -t gcr.io/${GOOGLE_CLOUD_PROJECT}/hello-cloud-run:v1 .

将镜像推送到 Google 容器镜像仓库:

docker push gcr.io/${GOOGLE_CLOUD_PROJECT}/hello-cloud-run:v1

部署到 Cloud Run

使用 gcloud run deploy 命令部署:

gcloud run deploy hello-cloud-run \
  --image gcr.io/${GOOGLE_CLOUD_PROJECT}/hello-cloud-run:v1 \
  --allow-unauthenticated
  • --allow-unauthenticated 表示公开访问,测试时可为服务生成公开 URL;生产环境建议通过 IAM 控制访问权限。
  • 部署时 Cloud Run 会提示设置服务名称、区域等参数,可直接回车使用默认值。

命令成功执行后,终端会返回服务 URL,例如:

Service [hello-cloud-run] revision [hello-cloud-run-00001-qeq] has been deployed and is serving 100 percent of traffic.
Service URL: https://hello-cloud-run-hash-uc.a.run.app

在浏览器中打开该 URL,就能看到 “Hello from Cloud Run!” 页面。

进阶配置要点

环境变量与密钥

通过 --set-env-vars 传递环境变量;敏感数据建议使用 Secret Manager 挂载。

示例:

gcloud run deploy hello-cloud-run \
  --image gcr.io/${PROJECT_ID}/hello-cloud-run:v1 \
  --set-env-vars "ENV=production,LOG_LEVEL=debug"

资源配置

每个实例可分配的 CPU 和内存上限可控。通过以下参数调整:

  • --cpu:虚拟 CPU 数(默认 1)
  • --memory:内存大小(如 256Mi, 512Mi, 1Gi 等)
  • --concurrency:每个实例最大并发请求数(默认 80)

示例:为计算密集型任务分配更多资源:

gcloud run deploy hello-cloud-run \
  --image gcr.io/${PROJECT_ID}/hello-cloud-run:v1 \
  --cpu 2 --memory 2Gi --concurrency 10

自动伸缩范围

设置最小和最大实例数,控制冷启动延迟与成本:

gcloud run deploy hello-cloud-run \
  --image ... \
  --min-instances 1 --max-instances 10
  • --min-instances 设为 1 可避免缩容到零导致的冷启动延迟,但会产生基础费用。
  • --max-instances 防止流量激增时成本失控。

连接到 Cloud SQL 或 VPC

需要将 Cloud Run 服务连接到 VPC 网络中的资源(如 Cloud SQL 私有 IP)时,使用 Serverless VPC Access 连接器。

  1. 创建连接器(需先启用 Serverless VPC Access API):
    gcloud compute networks vpc-access connectors create my-connector \
      --region us-central1 \
      --range "10.8.0.0/28"
    
  2. 部署时指定连接器:
    gcloud run deploy ... --vpc-connector my-connector