上一篇折騰了 [k8s 如何跑 go 服務](https://zhuanlan.zhihu.com/p/248866126 k8s運行go服務), 並且對 k8s 基礎概念 deployment / replicaSet / pod 進行了詳細的講解
實踐過的小夥伴可能會繼續追問: 好多好多步驟呢, 尤其是寫 deployment.yml
文件時, 還挺折騰的, 敢不敢更簡單點?
一如既往: 敢!
服務鏡像準備
首先, 還是老三樣, 準備好我們的鏡像
- go 服務代碼, 還是簡單的 hello 爲例
這裏使用了 環境變量, 方便後續演示: 可以通過環境變量這種方式來控制應用
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
username := os.Getenv("USERNAME")
if username == "" {
username = "world"
}
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintf(writer, "hello %s\n\n", username)
})
http.ListenAndServe(":" + port, nil)
}
- Dockerfile 構建鏡像, 依舊是 兩階段構建
FROM golang:alpine as builder
WORKDIR /app
COPY main.go .
RUN go build -o hello main.go
FROM alpine
WORKDIR /app
ARG PORT=80
COPY --from=builder /app/hello /app/hello
ENTRYPOINT ./hello
EXPOSE 80
- alibaba cloud toolkit 上傳鏡像, 依舊是一件搞定
helm: 主角登場
介紹一下概念, 方便理解:
- helm: k8s 的包管理工具, 能把 k8s 的應用/服務 打包好
- chart: helm 中對 k8s 中 應用/服務 的抽象, 簡單理解
chart = k8s 應用
不廢話, 直接一頓操作猛如虎:
brew info helm # 安裝 helm
helm init hello # 初始化一個 helm chart 工程
➜ tree -L 2
.
├── Chart.yaml # chart 的基礎新
├── charts
├── templates # k8s 的標準 yaml 文件
│ ├── NOTES.txt
│ ├── _helpers.tpl
│ ├── deployment.yaml
│ ├── hpa.yaml
│ ├── ingress.yaml
│ ├── service.yaml
│ ├── serviceaccount.yaml
│ └── tests
└── values.yaml # 主要需要修改的文件, 值都在這裏定期, 供 templates 下的文件使用
只需要修改 2 個文件:
-
deployment.yaml
: 把環境變量加上
containers:
- name: {{ .Chart.Name }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
env: # 添加環境變量
- name: USERNAME
value: {{ .Values.Username }}
-
values.yaml
: 修改鏡像地址 + 配置環境變量
image:
repository: registry.cn-shanghai.aliyuncs.com/daydaygo/open
pullPolicy: IfNotPresent
# Overrides the image tag whose default is the chart appVersion.
tag: "20200917224128"
Username: dayday
繼續 helm 操作:
helm lint --strict hello # lint: 校驗
➜ helm package hello # package: 打包
Successfully packaged chart and saved it to: /Users/dayday/coder_at_work/docker/k8s/helm_test/hello-0.1.0.tgz
➜ helm install hello hello-0.1.0.tgz # install: 安裝
NAME: hello
LAST DEPLOYED: Thu Sep 17 22:54:54 2020
NAMESPACE: default
STATUS: deployed
REVISION: 1
NOTES:
1. Get the application URL by running these commands:
export POD_NAME=$(kubectl get pods --namespace default -l "app.kubernetes.io/name=hello,app.kubernetes.io/instance=hello" -o jsonpath="{.items[0].metadata.name}")
echo "Visit http://127.0.0.1:8080 to use your application"
kubectl --namespace default port-forward $POD_NAME 8080:80
➜ kubectl port-forward hello-ffbd5b4d7-bhwtp 3000:80 # port-forward: 端口轉發, 方便本地測試
Forwarding from 127.0.0.1:3000 -> 80
Forwarding from [::1]:3000 -> 80
➜ curl localhost:3000 # 大功告成
hello dayday
寫在最後
很簡單有木有, 趕緊也動手試試
更多例子: cloudnativeapp/handbook
伴隨着雲原生生態的不斷髮展與壯大, 標準/工具鏈越發的成熟, 服務的部署與運維會越來越 easy, 一起期待更美好的明天~
我是 dayday, 讀書寫作敲代碼, 永遠在路上