赠书 | 如何部署一个Knative Service
我們以一個go語言編寫的程序代碼為例,創建一個簡單的Web服務,當該服務接收到HTTP GET請求時會根據環境變量TARGET傳遞的內容向response輸出Hello $TATGET! 內容。
1. 創建一個文件名為helloworld.go的文件。程序源碼如下:
package mainimport ("fmt""log""net/http""os")func handler(w http.ResponseWriter, r *http.Request) { log.Print("helloworld: received a request") target := os.Getenv("TARGET")if target == "" { target = "World" } fmt.Fprintf(w, "Hello %s!\n", target)}func main() { log.Print("helloworld: starting server...")http.HandleFunc("/", handler)port := os.Getenv("PORT")if port == "" { port = "8080" }log.Printf("helloworld: listening on port %s", port) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))}使用下面內容的Dockerfile構建源碼并生成容器:
# Use the official Golang image to create a build artifact.# This is based on Debian and sets the GOPATH to /go.# https://hub.docker.com/_/golangFROM golang:1.13 as builder# Create and change to the app directory.WORKDIR /app# Retrieve application dependencies using go modules.# Allows container builds to reuse downloaded dependencies.COPY go.* ./RUN go mod download# Copy local code to the container image.COPY . ./# Build the binary.# -mod=readonly ensures immutable go.mod and go.sum in container builds.RUN CGO_ENABLED=0 GOOS=linux go build -mod=readonly -v -o server# Use the official Alpine image for a lean production container.# https://hub.docker.com/_/alpine# https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-buildsFROM alpine:3RUN apk add --no-cache ca-certificates# Copy the binary to the production image from the builder stage.COPY --from=builder /app/server /server# Run the web service on container startup.CMD?["/server"] # 在本地主機構建容器。{username}替換為你自己在dockerhub的用戶名。docker build -t {username}/helloworld-go .# 將容器Push到Docker容器鏡像倉庫。{username}替換為你自己在dockerhub的用戶名。docker push {username}/helloworld-go?部署Knative Service?
Knative Service和其他Kubernetes資源類似,可以通過一個YAML文件進行定義和部署。接下來我們使用上一步構建的容器來部署Knative Service服務。service.yaml配置文件如下:
apiVersion: serving.knative.dev/v1kind: Servicemetadata:name: helloworld-go # Service名稱namespace: defaultspec:template:metadata:name: helloworld-go-v1 # Knative Revision名稱,如果未設置系統將會自動生成。spec:containers:- image: {username}/helloworld-goenv:- name: TARGETvalue: "Go Sample v1"livenessProbe:httpGet:path: /readinessProbe:httpGet:????????????path:?/運行下面的命令部署helloworld-go Knative Service:
# kubectl apply -f service.yaml在這個YAML配置文件中,Knative Service的kind的值是Service,為了避免與Kubernetes內置的service混淆,apiVersion的值需要設置為serving.knative.dev/v1。
配置文件中的spec區塊與Kubernetes PodSpec的定義幾乎完全一樣,只是刪除了以下屬性:
? InitContainers? RestartPolicy? TerminationGracePeriodSeconds? ActiveDeadlineSeconds? DNSPolicy? NodeSelector? AutomountServiceAccountToken? NodeName? HostNetwork? HostPID? HostIPC? ShareProcessNamespace? SecurityContext? Hostname? Subdomain? Affinity? SchedulerName? Tolerations? HostAliases? PriorityClassName? Priority? DNSConfig? ReadinessGates??RuntimeClassNamespec.template.metadata.name定義了Knative Revision的名稱,這個名稱是可選的,如果被省略,Revision的名稱會自動生成。
Knative Service的liveness探針與標準Kubernetes探針有微小區別。Knative Service探針定義中沒有port屬性定義。Knative Serving控制器在service部署階段能夠自動確定port值。readiness探針也遵循同樣的規則。
檢查部署結果并驗證服務:
# kubectl get ksvc helloworld-goNAME URL LATESTCREATED LATESTREADY READY REASONhelloworld-go???http://helloworld-go.default.example.com???helloworld-go-v1???helloworld-go-v1???True通過curl命令訪問helloworld-go服務:
##獲取集群任一節點的IP地址和nodePort端口# IP_ADDRESS="$(kubectl get nodes -o 'jsonpath={.items[0].status.addresses[0].address}'):$(kubectl get svc istio-ingressgateway --namespace istio-system --output 'jsonpath={.spec.ports[?(@.port==80)].nodePort}')"# curl -H "Host:helloworld-go.default.example.com" http://$IP_ADDRESSHello Go Sample v1!上面的腳本中為了獲取可以訪問到helloworld-go服務的ip地址以端口號,我們選取了集群任一節點的ip地址,istio-ingressgateway服務的nodePort端口號。使用帶有Service URL的主機名的頭信息(例如Host:helloworld-go.default.example.com)即可訪問helloworld-go服務了。
當curl訪問到服務后,knative Serving自動創建了一個pod副本提供服務,當一段時間沒有訪問服務后,pod副本將會被銷毀。我們可以通過watch kubectl get pods 來監控pod的生命周期。
本文摘編于機械工業出版社出版的圖書《Knative實戰:基于Kubernetes的無服務器架構實踐》。
本書的讀者對象:
對Serverless技術感興趣的讀者。
想要將Knative引入當前技術棧的架構師。
想要采用Serverless技術的應用開發者。
想要自己維護Knative Serverless平臺的運維開發人員。
關于作者:
李志偉?某網云原生實驗室負責人,容器云領域專家。在Kubernetes、Istio、Serverless、DevOps工具等領域有深入的研究和實踐。熱心于云原生技術的應用與推廣,曾榮獲“K8sMeetup中國社區”最受歡迎講師獎項。
游楊??某網云原生實驗室高級運維開發工程師。先后參與Kubernetes和Knative項目的落地與實施工作,擁有豐富的容器平臺實踐經驗,聚焦于Kubernetes、Serverless、CI/CD技術領域。
對于Knative,你有哪些了解?
#歡迎來評論區討論#
CSDN云計算?將選出三名優質留言
攜手【機械工業出版社華章分社】送出
《Knative實戰:基于Kubernetes的無服務器架構實踐》一本
截至4月27日14:00點
60+專家,13個技術領域,CSDN?《IT 人才成長路線圖》重磅來襲!
直接掃碼或微信搜索「CSDN」公眾號,后臺回復關鍵詞「路線圖」,即可獲取完整路線圖!
更多精彩推薦 ?5G、射頻、奧特曼,這仨有聯系嗎??再見 Nacos,我要玩 Service Mesh 了!?用根因定位法,讓運維效率再高一點!點分享點收藏點點贊點在看 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的赠书 | 如何部署一个Knative Service的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深度揭秘:腾讯存储技术发展史
- 下一篇: 到底是谁发明了物联网?