跳到主要内容

Cloud Run 示例

Github StackBlitz

本示例演示了如何将 Go Fiber 应用程序部署到 Google Cloud Run。

描述

本项目提供了一个将 Go Fiber 应用程序部署到 Google Cloud Run 的起点。它包含了使用 Docker 和 Google Cloud Build 构建和部署应用程序所需的配置文件和脚本。

要求

设置

  1. 克隆仓库

    git clone https://github.com/gofiber/recipes.git
    cd recipes/cloud-run
  2. 安装依赖

    go mod download
  3. 构建 Docker 镜像

    docker build -t cloud-run-example .
  4. 运行 Docker 容器

    docker run -p 3000:3000 cloud-run-example

应用程序现在应该运行在 http://localhost:3000

部署到 Google Cloud Run

  1. 设置 Google Cloud SDK 并进行身份验证

    gcloud auth login
    gcloud config set project [YOUR_PROJECT_ID]
  2. 使用 Google Cloud Build 构建并推送 Docker 镜像

    gcloud builds submit --tag gcr.io/[YOUR_PROJECT_ID]/cloud-run-example
  3. 将镜像部署到 Cloud Run

    gcloud run deploy cloud-run-example --image gcr.io/[YOUR_PROJECT_ID]/cloud-run-example --platform managed --region [YOUR_REGION] --allow-unauthenticated

[YOUR_PROJECT_ID][YOUR_REGION] 替换为您的 Google Cloud 项目 ID 和所需的区域。

Cloud Build 配置

cloudbuild.yaml 文件定义了使用 Google Cloud Build 构建和部署应用程序的步骤

steps:
- name: 'gcr.io/kaniko-project/executor:latest'
id: 'build-and-push'
args:
- '--destination=asia.gcr.io/$PROJECT_ID/$_SERVICE_NAME:$SHORT_SHA'
- '--destination=asia.gcr.io/$PROJECT_ID/$_SERVICE_NAME:latest'
- '--dockerfile=Dockerfile'
- '--context=.'
- '--cache=true'
- '--cache-ttl=120h'

- id: 'Deploy to Cloud Run'
name: 'gcr.io/cloud-builders/gcloud'
entrypoint: 'bash'
args:
- '-c'
- |
gcloud run deploy $_SERVICE_NAME \
--image=asia.gcr.io/$PROJECT_ID/$_SERVICE_NAME:$SHORT_SHA \
--region=$_REGION --platform managed --allow-unauthenticated \
--port=3000
options:
substitutionOption: ALLOW_LOOSE

substitutions:
_SERVICE_NAME: cloud-run-example
_REGION: asia-southeast1

示例用法

  1. 打开您的浏览器并导航到部署后提供的 Cloud Run 服务 URL。

  2. 您应该会看到消息:Hello, World!

结论

本示例提供了将 Go Fiber 应用程序部署到 Google Cloud Run 的基本设置。可以进一步扩展和定制,以满足更复杂应用程序的需求。

参考资料