Google Cloud Run创建服务API调用返回404错误求助
Google Cloud Run API 创建服务时404错误的解决方法
核心问题拆解
1. API端点URL错误
创建服务的POST请求必须指向服务集合端点,而非单个服务的详情路径。你当前的URL包含了{service_id},这是用于查询/更新已有服务的地址,创建新服务时不需要在URL中指定service_id,正确的端点应去掉该部分。
2. 请求体格式不符合API规范
你的请求体存在多处格式问题,这也是之前触发400字段违规错误的原因:
name字段不能为空,必须填写完整的资源名称(格式为projects/{project_id}/locations/{region}/services/{service_id})containers要求是数组类型,而非单个对象(Cloud Run支持多容器部署,即使只部署一个容器也需要用数组包裹)- 手动设置
generation字段无意义,API会自动生成该值,应删除 - 镜像地址格式错误,重复了
gcr.io前缀,需修正为合法的容器镜像路径
修复后的完整代码
import requests project_id = "你的项目ID" region = "你的部署区域" service_id = "待创建的服务ID" access_token = "你的访问令牌" # 修正后的创建服务API端点 url = f"https://run.googleapis.com/v2/projects/{project_id}/locations/{region}/services" headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } body = { # 完整的服务资源名称 "name": f"projects/{project_id}/locations/{region}/services/{service_id}", "description": "test", "labels": { "cloud.googleapis.com/location": region }, "template": { # containers改为数组格式 "containers": [ { # 修正镜像地址,移除重复的gcr.io前缀 "image": f"gcr.io/{project_id}/test1:v01" } ] } } response = requests.post(url, headers=headers, json=body) if response.status_code in (200, 201): service_details = response.json() print("服务创建成功:") print(service_details) else: print(f"错误: {response.status_code} - {response.text}")
额外注意事项
- 确保你的访问令牌拥有
run.services.create权限,可通过IAM角色(如roles/run.admin)授予 - 容器镜像必须是Google Container Registry或Artifact Registry中存在的可访问镜像,且服务账号有权拉取该镜像
- Cloud Run创建服务的API通常返回201表示成功创建,部分异步场景会返回200,因此判断时需包含这两个状态码
内容的提问来源于stack exchange,提问作者Fl0k1
相关产品推荐
相关产品推荐

