基于Gitlab+Kubernetes实现CI/CD

要求

基本技术栈要求如下:

  1. Golang
  2. Docker
  3. GitLab
  4. Kubernetes

具体原因参考关于技术选型的思考

步骤

创建Kubernetes集群

自己搭建集群也可以,但是投入生产不建议使用。这里直接使用google cloud(调研几家发现G家这方面技术积累最深,生态完整)。

创建帐号设置gitlab操作帐号,用于后面的CI/CD操作。

kubectl apply -f gitlab-admin-service-account.yaml
kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep gitlab-admin | awk '{print $1}')

具体参考Adding and creating a new GKE cluster via GitLab

创建DockerHub帐号

主要操作是在DockerHub创建帐号。 其他的云计算服务的镜像服务也可以。

创建gitlab项目

正常创建代码仓库操作。

准备代码

准备一个简单的web服务器。

package main

import (
  "fmt"
  "net/http"
)

func main() {
  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, k8s-go!")
  })

  http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Health OK!")
  })

  http.ListenAndServe(":8090", nil)
}

DockerFile

FROM golang:1.11-alpine as builder
WORKDIR /usr/build
ADD main.go .
RUN go build -o k8s-app .

FROM alpine:latest

WORKDIR /usr/src

COPY --from=builder /usr/build/k8s-app .
EXPOSE 8090

CMD ["/usr/src/k8s-app"]

配置docker环境变量

docker环境变量

设置对应用户名与密码即可。

配置Kubernetes集群环境变量

主要配置下图三个变量(用于连接Kubernetes集群):

Kubernetes集群环境变量

CERTIFICATE_AUTHORITY_DATA

cat  ~/.kube/config   | grep certificate-authority-data   | tr -d  '\n'    | grep certificate-authority-data     |  awk   '{print $2}'

USER_TOKEN

kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep gitlab-admin | awk '{print $1}')

SERVER

kubectl cluster-info  | grep master

从输出结果中获取master对应url即可。

设置deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: k8s-go
  labels:
    app: go
spec:
  replicas: 3
  selector:
    matchLabels:
      app: go
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 33%
  template:
    metadata:
      labels:
        app: go
    spec:
      containers:
        - name: go
          image: <yourdockerhubname>/<yourimagename>:<VERSION>
          ports:
            - containerPort: 8090
          livenessProbe:
            httpGet:
              path: /healthz
              port: 8090
            initialDelaySeconds: 2
            periodSeconds: 2
          readinessProbe:
            httpGet:
              path: /healthz
              port: 8090
            initialDelaySeconds: 2
            periodSeconds: 2
---
kind: Service
apiVersion: v1
metadata:
  name: k8s-go-loadbalancer-service
spec:
  selector:
    app: go
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8090
  type: LoadBalancer

设置CI/CD

gitlab.yml内容如下:

image: docker:latest
services:
  - docker:dind

stages:
  - build
  - deploy

variables:
  CONTAINER_IMAGE: <yourdockerhubname>/<yourimagename>:${CI_COMMIT_SHORT_SHA}

build:
  stage: build
  script:
    - docker login -u ${DOCKER_USER} -p ${DOCKER_PASSWORD}
    - docker build -t ${CONTAINER_IMAGE} .
    - docker tag ${CONTAINER_IMAGE} ${CONTAINER_IMAGE}
    - docker tag ${CONTAINER_IMAGE} <yourdockerhubname>/<yourimagename>:latest
    - docker push ${CONTAINER_IMAGE}

deploy:
  stage: deploy
  image: dtzar/helm-kubectl
  script:
    - kubectl config set-cluster k8s --server="${SERVER}"
    - kubectl config set clusters.k8s.certificate-authority-data ${CERTIFICATE_AUTHORITY_DATA}
    - kubectl config set-credentials gitlab --token="${USER_TOKEN}"
    - kubectl config set-context default --cluster=k8s --user=gitlab
    - kubectl config use-context default
    - sed -i "s/<VERSION>/${CI_COMMIT_SHORT_SHA}/g" deployment.yaml
    - kubectl apply -f deployment.yaml

测试CI/CD

CI/CD状态

CI/CD检查

提交代码自动部署

部署迁移

如何将部署迁移到其他的集群,在配置好新的集群后,只需要重新配置相关Kubernetes环境变量即可。

参考

  1. 更快部署代码:CI/CD 与 Kubernetes
  2. GitLab + Kubernetes: Using GitLab CI’s Kubernetes Cluster feature

(end)

欢迎关注

欢迎关注微信公众帐号:沉风网事(savewind)

沉风网事

Share Comments
comments powered by Disqus