Google Cloud Run 部署Knative Serverless 应用

水深无声 2022-01-30 23:25 229阅读 0赞

Google Cloud Run 部署Knative Serverless 应用

Google Cloud Run 是 Google 最近推出的基于容器运行的支持 Serverless 应用的服务,是 Knative 的Google Cloud 托管版本;和其他的 Serverless 如Google Cloud Functions, AWS Lambda 等相比,优点在于完全的基于容器,且不限语言

安装 Cloud SDK

Cloud SDK 是 Google Cloud 的命令行工具,用于访问Google Cloud相关资源

具体平台的安装方式可以参考 https://cloud.google.com/sdk/docs/quickstarts

创建应用,上传镜像

以 Go 语言为例,创建一个应用,根据不同的请求返回不同的内容

  • main.go

    package main

    import (

    1. "encoding/json"
    2. "fmt"
    3. "net/http"
    4. "net/url"

    )

    type CustomResponse struct {

    1. Code int `json:"code"`
    2. Message string `json:"message"`

    }

    func main() {

    1. fmt.Println("Server started")
    2. http.HandleFunc("/", rootHandler)
    3. _ = http.ListenAndServe(":8080", nil)

    }

    func rootHandler(w http.ResponseWriter, r *http.Request) {

    1. fmt.Println("Start handler request")
    2. queryForm, err := url.ParseQuery(r.URL.RawQuery)
    3. w.Header().Set("Content-Type", "application/json")
    4. message := ""
    5. if err == nil && len(queryForm["message"]) > 0 {
    6. message = queryForm["message"][0]
    7. } else {
    8. message = "Hello Go Server"
    9. }
    10. _ = json.NewEncoder(w).Encode(CustomResponse{ 200, message})
    11. fmt.Println("Handler request completed")

    }

  • Dockerfile

    FROM golang:1.12.3-alpine3.9
    RUN mkdir /app
    ADD . /app/
    WORKDIR /app
    RUN CGO_ENABLED=0 GOOS=linux go build -o main main.go
    EXPOSE 8080
    CMD [“/app/main”]

  • 配置 Google Container Registry

相关配置可以参考 推送和拉取映像,需要注意的是需要一个项目 ID,这个 ID 可以在 home/dashboard 下找到

Google Porject

  • 配置本地 Docker

    gcloud auth configure-docker

  • 构建镜像

    docker build -t gcr.io/genial-post-128203/serverless .

  • 推送镜像

    docker push gcr.io/genial-post-128203/serverless

创建 Serverless 应用

在Cloud Run 页面选择创建服务

创建服务

服务详情

测试

请求 URL https://cloudserverless-pae2opltia-uc.a.run.app

  • 不带参数

    curl https://cloudserverless-pae2opltia-uc.a.run.app

    { “code”:200,”message”:”Hello Go Server”}

  • 指定参数

    curl https://cloudserverless-pae2opltia-uc.a.run.app?message=HelloWood

    { “code”:200,”message”:”HelloWood”}


代码

  • https://github.com/helloworlde/google-cloud-run-go

参考资料

  • Google Cloud Run详细介绍
  • 推送和拉取映像
  • Using System Packages Tutorial

发表评论

表情:
评论列表 (有 0 条评论,229人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Knative 简介

    本文作者来自蚂蚁金服系统部之芥 什么是 Knative? [knative][] 是谷歌开源的 serverless 架构方案,旨在提供一套简单易用的 serverle