本篇主要讲解如何将golang的服务部署到kubernetes集群里,附带相关的golang的demo和yml文件内容。纯新手入门方式,生产服务需要完整的CI/CD流程来支持。
golang服务代码这里简单写一个k8s-demo的服务,提供两个接口ping和version接口,main.go文件代码如下:
package mainimport (
"net/http"
"github.com/gin-gonic/gin"
)
func statusOKHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func versionHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"version": "v1.0"})
}
func main() {
router := gin.New()
router.Use(gin.Recovery())
router.GET("/ping", statusOKHandler)
router.GET("/version", versionHandler)
router.Run(":8080")
}
构建命令:CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o k8s-demo main.go
Dockerfile文件这里只提供最基础的demo写法,如果有额外的需求在dockerfile文件内补充就行,Dockerfile文件内容如下:
FROM alpineADD k8s-demo /data/app/
WORKDIR /data/app/
CMD ["/bin/bash","-c","./k8s-demo"] CI构建脚本
写一个build.sh,用于编译二进制文件,然后进行docker镜像打包和推送进行到镜像仓库:
#!/bin/bashset -e
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o k8s-demo main.go
docker build -t :1.0 .
docker push :1.0
执行build.sh脚本文件即可,请确保此步骤成功将镜像推送到你的镜像仓库里。
kubernetes部署准备创建deployment的yaml文件
kubernetes版本1.18,我这里使用yaml文件创建deployment来部署k8s-demo服务到k8s集群里,k8s-demo.yaml文件内容如下:
---apiVersion: apps/v1
kind: Deployment
metadata:
name: k8s-demo
namespace: default
labels:
app: k8s-demo
spec:
selector:
matchLabels:
app: k8s-demo
replicas: 4
revisionHistoryLimit: 10
minReadySeconds: 5
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
template:
metadata:
labels:
app: k8s-demo
spec:
containers:
- image: :1.0
imagePullPolicy: IfNotPresent
name: k8s-demo
ports:
- containerPort: 8080
protocol: TCP
resources:
limits:
cpu: 100m
memory: 100Mi
requests:
cpu: 50m
memory: 50Mi
livenessProbe:
tcpSocket:
port: 8080
initialDelaySeconds: 10
timeoutSeconds: 3
readinessProbe:
httpGet:
path: /ping
port: 8080
initialDelaySeconds: 10
timeoutSeconds: 2
---
apiVersion: v1
kind: Service
metadata:
name: k8s-demo-svc
namespace: default
labels:
app: k8s-demo
spec:
ports:
- name: api
port: 8080
protocol: TCP
targetPort: 8080
selector:
app: k8s-demo
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: k8s-demo-ingress
namespace: default
spec:
rules:
- host: k8s-demo.local
http:
paths:
- path: /
backend:
serviceName: k8s-demo-svc
servicePort: api
此yaml文件里主要定义了三种资源:deployment、service、ingress,都配置在默认的namespace里,yaml文件里的每项内容做什么用的下一篇再补充,这里先把服务部署起来找找成就感!
k8s部署
在已经搭建好k8s环境的master节点里使用kubectl命令来执行部署,命令如下:
kubectl apply -f k8s-demo.yaml执行效果如下:
稍等会通过通过查询pods列表的命令:kubectl get pods 来查看pod运行状态,如下图: