1.工程目录结构
2.先添加一个简单的golang服务
main.go
package main
import (
"flag"
"net/http"
"os"
"github.com/gin-gonic/gin"
)
var version = flag.String("v", "v1", "v1")
func main() {
router := gin.Default()
router.GET("", func(c *gin.Context) {
flag.Parse()
hostname, _ := os.Hostname()
c.String(http.StatusOK, "This is version:%s running in pod %s", *version, hostname)
})
router.Run(":8080")
}
3.在终端执行如下命令
go mod init test #给工程创建一个go mod 管理工程
go get github.com/gin-gonic/gin #下载包
go build main.go #编译mian.go
4.编写Dockerfile
FROM golang:latest AS build
WORKDIR /test
COPY . /test
RUN go env -w GOPROXY=https://goproxy.cn,direct
RUN CGO_ENABLED=0 go build -v -o main .
FROM alpine AS api
RUN mkdir /app
COPY --from=build /test/main /app
WORKDIR /app
ENTRYPOINT ["./main", "-v" ,"1.3"]
5.构建docker镜像并保存为tar包
docker build -t go:v1.3 .
docker tag go:v1.3 foxliang/go:v1.3
docker save foxliang/go -o foxliang2.tar
6.将镜像导入containerd中
ctr -n k8s.io i import foxliang2.tar
7.将镜像通过yaml部署到k8s(编写test.yaml)
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: go-deployment
labels:
app: go
spec:
selector:
matchLabels:
app: go
replicas: 3
minReadySeconds: 5
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
template:
metadata:
labels:
app: go
spec:
containers:
- image: foxliang/go:v1.3
name: go
imagePullPolicy: Always
command: ["./main","-v","v1.3"]
ports:
- containerPort: 8080
protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
name: go-service
labels:
app: go
spec:
selector:
app: go
ports:
- name: go-port
protocol: TCP
port: 8080
targetPort: 8080
nodePort: 31080
type: NodePort
8.部署
kubectl create -f test.yaml
9.查看pod状态
[root@node-2 ~]# kubectl get pod -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
go-deployment-769587fc8b-76p6c 1/1 Running 0 44m 10.232.4.243 node-8 <none> <none>
go-deployment-769587fc8b-m22jm 1/1 Running 0 44m 10.232.5.65 node-5 <none> <none>
go-deployment-769587fc8b-mthhh 1/1 Running 0 44m 10.232.3.108 node-4 <none> <none>
10.在浏览器访问服务
http://nodeIP:31080/
参考博客: