通过如下几步可以将自己的go应用部署到k8s上
首先生成自己的go项目
mkdir src cd src go mod init servertest
编写测试代码main.go内容如下,很简单
package main import ( "github.com/gin-gonic/gin" "fmt" "time" "net/http" ) type getTimeResp struct { CTime string } func getTimeHandler(ctx *gin.Context) { content := fmt.Sprintf("%d", time.Now().Nanosecond()) fmt.Printf("%s\n", content) resp := &getTimeResp{ CTime:content, } ctx.JSON(http.StatusOK, resp) } func main() { r := gin.Default() r.GET("/gettime", getTimeHandler) r.Run(":8000") }
编写Dockerfile内容如下
FROM golang:1.17.1-alpine as builder ENV GOPROXY=https://goproxy.cn WORKDIR /build COPY ./src . RUN go mod tidy RUN go build FROM alpine:latest RUN mkdir -p /cmd WORKDIR /cmd COPY --from=builder /build/servertest . EXPOSE 8000 CMD ["./servertest"]
生成镜像,执行命令
docker build -t servertest:1.0.0 -f Dockerfile .
执行
docker images
可以看到生成的servertest:1.0.0镜像已经存在了
因为k8s集群会存在多个nod所以多个nod都需要拉取镜像,所以需要保自己的镜像推到镜像服务器,我这里选用阿里的。
先登陆->将自己生成的镜像打tag->推到镜像服务器docker login --username=your_loginname_xxxx registry.cn-shanghai.aliyuncs.com docker tag servertest:1.0.0 registry.cn-shanghai.aliyuncs.com/your_hubname_xxxx/servertest:1.0.0 docker push registry.cn-shanghai.aliyuncs.com/your_hubname_xxxx/servertest:1.0.0
编写deployment和service配置文件
deployment.yaml文件内容如下apiVersion: apps/v1 kind: Deployment metadata: name: my-go-app spec: replicas: 3 selector: matchLabels: app: my-go-app template: metadata: labels: app: my-go-app spec: containers: - name: go-app-container image: registry.cn-shanghai.aliyuncs.com/your_hubname_xxxx/servertest:1.0.0 imagePullPolicy: IfNotPresent resources: limits: memory: "512Mi" cpu: "500m" requests: memory: "64Mi" cpu: "100m" ports: - containerPort: 8000
service.yaml内容如下
apiVersion: v1 kind: Service metadata: name: servertest-service spec: type: NodePort ports: - port: 8000 nodePort: 30066 selector: app: my-go-app
需要对外提供服务所以type选NodePort
port:8000是对应pod的端口号
nodePort:30066是service对外提供的调用端口号部署
执行kubectl create -f ./yaml/deployment.yaml kubectl create -f ./yaml/service.yaml
查看pod和service状况
kubectl get pod,svc -n default
可以看到如下
三个pod(my-go-app-xxxxxx-xxxx)处在Running状态
service的Port30066对外提供服务- 访问确认
查看任何一个node的物理IP地址,通过访问node主机的IP:30066/gettime
会返回当前时间(nano second)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。