HelloWood

Google Cloud Run 部署 Knative Serverless 应用

2019-05-15

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
1
2
3
4
5
6
7
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
1
gcloud auth configure-docker
  • 构建镜像
1
docker build -t gcr.io/genial-post-128203/serverless .
  • 推送镜像
1
docker push gcr.io/genial-post-128203/serverless

创建 Serverless 应用

Cloud Run 页面选择创建服务

创建服务

服务详情

测试

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

  • 不带参数
1
curl https://cloudserverless-pae2opltia-uc.a.run.app
1
{"code":200,"message":"Hello Go Server"}
  • 指定参数
1
curl https://cloudserverless-pae2opltia-uc.a.run.app?message=HelloWood
1
{"code":200,"message":"HelloWood"}

代码

参考资料