将 Go 服务部署到 GCP Cloud Run 涉及多个步骤,包括设置 Dockerfile 和配置环境变量。
本指南将引导您完成整个过程。
设置您的 GCP 项目
如果尚未创建帐户,请先转到 GCP 创建帐户。
- 创建一个 GCP 项目。
前往 GCP 控制台并创建一个新项目。
记下部署的项目 ID。
- 启用所需的 API。
- 启用 Cloud Run API 和 Container Registry API。
- 安装 Google Cloud SDK
- 使用 gcloud init 初始化您的存储库。
创建您的 Go 服务
确保您的 Go 应用可以在本地运行并设置 Dockerfile。
cmd/main.go
// cmd/main.go func main() { flag.Parse() a := app.Application{} if err := a.LoadConfigurations(); err != nil { log.Fatalf("Failed to load configurations: %v", err) } if err := runtime.Start(&a); err != nil { log.Fatalf("Failed to start the application: %v", err) } }
运行时/base.go
func Start(a *app.Application) error { router := gin.New() router.Use(cors.New(md.CORSMiddleware())) api.SetCache(router, a.RedisClient) api.SetRoutes(router, a.FireClient, a.FireAuth, a.RedisClient) err := router.Run(":" + a.ListenPort) log.Printf("Starting server on port: %s", a.ListenPort) if err != nil { return err } return nil }
创建 Dockerfile
# Use the official Go image as the base image FROM golang:1.18 WORKDIR /app # Copy the Go module files COPY go.mod go.sum ./ RUN go mod download # Copy the rest of the application code COPY . . RUN go build -o main ./cmd/main.go CMD ["./main"]
设置环境变量
使用 shell 脚本自动设置 GCP 的环境变量
作为env-variables.sh.
// env-variables.sh #!/bin/bash # Environment variables export PROJECT_ID=recepies-6e7c0 export REGION=europe-west1 export REDIS_URL="rediss://default:AVrvA....-lemur-23279.u....:6379" export FIREBASE_ACCOUNT_KEY="/app/config/account_key.json" export CLIENT_URL="https://.....vercel.app/"
部署脚本为deploy-with-yaml.sh.
#!/bin/bash source env-variables.sh #Comment if correctly deployed docker build -t gcr.io/$PROJECT_ID/recipe-server:latest . docker push gcr.io/$PROJECT_ID/recipe-server:latest #Uncomment if json needs to be added to GCP # gcloud secrets create firebase-account-key --data-file=/mnt/c/own_dev/RecipesApp/server/config/account_key.json --project=recepies-6e7c0 #Add permission IAM gcloud projects add-iam-policy-binding recepies-6e7c0 \ --member="serviceAccount:service-988443547488@serverless-robot-prod.iam.gserviceaccount.com" \ --role="roles/artifactregistry.reader" gcloud run deploy recipe-service \ --image gcr.io/$PROJECT_ID/recipe-server:latest \ --region $REGION \ --platform managed \ --set-env-vars REDIS_URL=$REDIS_URL,CLIENT_URL=$CLIENT_URL,FIREBASE_ACCOUNT_KEY=$FIREBASE_ACCOUNT_KEY
部署到您的 GCP Cloud Run
运行部署脚本
env-variables.sh
常见问题和故障排除
- 权限问题:确保 Cloud Run Service Agent 具有读取图像的权限。
- 环境变量:验证所有必需的环境变量是否设置正确。
- 端口配置:确保 PORT 环境变量设置正确。
根据需要完成所有设置后,您将看到正在构建映像并将其推送到您的 GCP 项目 Artifact Registry。最后我得到了这个。
a9099c3159f5: Layer already exists latest: digest: sha256:8c98063cd5b383df0b444c5747bb729ffd17014d42b049526b8760a4b09e5df1 size: 2846 Deploying container to Cloud Run service [recipe-service] in project [recepies-6e7c0] region [europe-west1] ✓ Deploying... Done. ✓ Creating Revision... ✓ Routing traffic... Done. Service [recipe-service] revision [recipe-service-00024-5mh] has been deployed and is serving 100 percent of traffic. Service URL: https://recipe-service-819621241045.europe-west1.run.app
有一个我多次遇到的标准错误?
Deploying container to Cloud Run service [recipe-service] in project [recepies-6e7c0] region [europe-west1] X Deploying… - Creating Revision… . Routing traffic… Deployment failed ERROR: (gcloud.run.deploy) Revision 'recipe-service-00005-b6h' is not ready and cannot serve traffic. Google Cloud Run Service Agent service-819621241045@serverless-robot-prod.iam.gserviceaccount.com must have permission to read the image, gcr.io/loyal-venture-436807-p7/recipe-server:latest. Ensure that the provided container image URL is correct and that the above account has permission to access the image. If you just enabled the Cloud Run API, the permissions might take a few minutes to propagate. Note that the image is from project [loyal-venture-436807-p7], which is not the same as this project [recepies-6e7c0]. Permission must be granted to the Google Cloud Run Service Agent service-819621241045@serverless-robot-prod.iam.gserviceaccount.com from this project. See https://cloud.google.com/run/docs/deploying#other-projects
通常它指出无法设置 PORT=8080,但主要问题是其他问题,例如未设置 env 变量,或者在我的情况下,firebase account_key.json 的部署设置不正确。
一切设置完毕后,您可以测试连接并执行请求。
我的前端部署在 Vercel 中,您可以在下面看到我的 Cloud Run 日志
通过一些关键配置和自动化脚本可以简化将 Go 服务部署到 GCP Cloud Run 的过程。
虽然可能会出现一些常见错误,例如权限问题或不正确的环境变量,但了解如何通过 Cloud Run 日志排查这些错误可确保部署顺利。
你可以在这里找到我的仓库。
以上是如何将 Go 服务部署到 GCP Cloud Run的详细内容。更多信息请关注PHP中文网其他相关文章!

Golang和Python的主要区别在于并发模型、类型系统、性能和执行速度。1.Golang使用CSP模型,适用于高并发任务;Python依赖多线程和GIL,适合I/O密集型任务。2.Golang是静态类型,Python是动态类型。3.Golang编译型语言执行速度快,Python解释型语言开发速度快。

Golang通常比C 慢,但Golang在并发编程和开发效率上更具优势:1)Golang的垃圾回收和并发模型使其在高并发场景下表现出色;2)C 通过手动内存管理和硬件优化获得更高性能,但开发复杂度较高。

Golang在云计算和DevOps中的应用广泛,其优势在于简单性、高效性和并发编程能力。1)在云计算中,Golang通过goroutine和channel机制高效处理并发请求。2)在DevOps中,Golang的快速编译和跨平台特性使其成为自动化工具的首选。

Golang和C 在执行效率上的表现各有优势。1)Golang通过goroutine和垃圾回收提高效率,但可能引入暂停时间。2)C 通过手动内存管理和优化实现高性能,但开发者需处理内存泄漏等问题。选择时需考虑项目需求和团队技术栈。

Golang更适合高并发任务,而Python在灵活性上更有优势。1.Golang通过goroutine和channel高效处理并发。2.Python依赖threading和asyncio,受GIL影响,但提供多种并发方式。选择应基于具体需求。

Golang和C 在性能上的差异主要体现在内存管理、编译优化和运行时效率等方面。1)Golang的垃圾回收机制方便但可能影响性能,2)C 的手动内存管理和编译器优化在递归计算中表现更为高效。

selectgolangforhighpperformanceandcorrency,ifealforBackendServicesSandNetwork程序; selectpypypythonforrapiddevelopment,dataScience和machinelearningDuetoitsverserverserverserversator versator anderticality andextility andextentensivelibraries。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。 Golang以其并发模型和高效性能着称,Python则以简洁语法和丰富库生态系统着称。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

Dreamweaver Mac版
视觉化网页开发工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。