You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何每日定时自动修改Cloud Run服务的最小实例配置

定时调整Cloud Run最小实例数方案

1. 编写Cloud Function(Python版)

这个函数负责调用Cloud Run API修改服务的最小实例数,你可以直接复用以下代码:

import os
from googleapiclient.discovery import build

def adjust_run_min_instances(request):
    # 从POST请求体获取目标实例数
    req_data = request.get_json()
    target_min = req_data.get('min_instances', 0)

    # 替换为你的实际配置,也可以通过环境变量传入
    project_id = "你的项目ID"
    service_name = "hello-world"
    region = "你的服务部署区域(如us-central1)"

    # 初始化Cloud Run客户端
    run_api = build('run', 'v1')
    service_full_path = f"projects/{project_id}/locations/{region}/services/{service_name}"

    # 获取当前服务配置
    current_service = run_api.projects().locations().services().get(name=service_full_path).execute()
    service_spec = current_service['spec']['template']['spec']

    # 更新最小实例数
    service_spec['minInstances'] = target_min

    # 提交更新请求
    update_req = run_api.projects().locations().services().patch(
        name=service_full_path,
        body={"spec": {"template": {"spec": service_spec}}},
        updateMask="spec.template.spec.minInstances"
    )
    update_req.execute()

    return f"已将最小实例数设置为 {target_min}", 200

部署注意事项

  • 部署函数时,给函数的默认服务账号添加Cloud Run Developer权限(足够修改实例数配置)
  • 如果不想硬编码项目ID等信息,可在部署时设置环境变量,代码里用os.environ.get()读取

2. 创建Cloud Scheduler定时任务

创建两个定时任务,分别控制早间升实例、夜间降实例:

任务1:早间启动预热实例

  • Cron表达式:0 8 * * *(UTC时间,可按需调整时区和具体时间)
  • 目标类型:HTTP
  • 目标URL:你的Cloud Function触发URL
  • 请求方法:POST
  • 请求体:{"min_instances": 1}

任务2:夜间关闭预热实例

  • Cron表达式:0 22 * * *(UTC时间,可按需调整时区和具体时间)
  • 目标类型:HTTP
  • 目标URL:同一个Cloud Function触发URL
  • 请求方法:POST
  • 请求体:{"min_instances": 0}

权限配置

  • 给Cloud Scheduler的服务账号添加Cloud Functions Invoker权限,确保能调用函数

内容的提问来源于stack exchange,提问作者Spartan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 23:22:18