Google Cloud Run 部署 Knative Serverless 应用

May 15, 2019 · 201 words · One minute

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 (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
)

type CustomResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func main() {
	fmt.Println("Server started")
	http.HandleFunc("/", rootHandler)
	_ = http.ListenAndServe(":8080", nil)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Start handler request")

	queryForm, err := url.ParseQuery(r.URL.RawQuery)

	w.Header().Set("Content-Type", "application/json")
	message := ""

	if err == nil && len(queryForm["message"]) > 0 {
		message = queryForm["message"][0]
	} else {
		message = "Hello Go Server"
	}

	_ = json.NewEncoder(w).Encode(CustomResponse{200, message})
	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"]

相关配置可以参考 推送和拉取映像,需要注意的是需要一个项目 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"}

代码

参考资料