1. jenkins上的操作

    • 在jenkins上新建一个多分支流水线作业
    • 在对应的Branch Sources处选择使用的分支来源
    • 在Build Confiiguration处的mode选择by Jenkinsfiles,表示以Jenkinsfies为系统部署的触发入口
    • 点击Save即可
  2. 代码上操作

    • 在项目的路径下新建Jenkinsfie文件,内容为
      pipeline {
      agent {
        label 'docker'
      }
      options {
       buildDiscarder(logRotator(numToKeepStr: '5', daysToKeepStr: '14'))
      }
      triggers {
      	pollSCM 'H/5 * * * *'
      }
      stages {
      stage('Build Image & Upload') {
          when {
              branch "对应部署的分支"
          }
          agent {
              label 'docker'
          }
          steps {
                withKubeConfig([
                      credentialsId: 'k8s配置在jenkins上的秘钥id',
                      contextName  : 'kubernetes']) {
                  sh 'chmod +x go'
                  sh './go build'
              }
          }
      }
      stage('deploy for prod') {
          agent {
              label 'docker'
          }
          when {
              branch '对应部署的分支'
          }
          environment {
             /*此处为对应的环境变量*/
          }
          steps {
              withKubeConfig([
                      credentialsId: 'k8s配置在jenkins上的秘钥id',
                      contextName  : 'kubernetes']) {
                  sh 'chmod +x go'
                  sh './go deploy'
              }
          }
        }
       }
      }
      
    • 由于上述文件执行的shell脚本的名称为go,所以在系统路径下创建go的shell脚本文件,内容如下
      #!/bin/bash
      
      set -e
      ENV=$SPRING_PROFILES_ACTIVE
      CI_COMMIT_SHA=${GIT_COMMIT:=$(git log -n 1 --pretty=format:'%h')}
      IMAGE_TAG="$CI_COMMIT_SHA"
      DOCKER_REGISTRY_SERVER=harbour服务器名称
      DOCKER_REGISTRY_NAME=$(echo $DOCKER_REGISTRY_SERVER | sed 's~http[s]*://~~g')
      DOCKER_USER=$(kubectl get secret regcred --output="jsonpath={.data.\.dockerconfigjson}" | base64 --decode | jq .[] | jq .[].username | sed -e 's/^"//' -e 's/"$//')
      DOCKER_PASSWORD=$(kubectl get secret regcred --output="jsonpath={.data.\.dockerconfigjson}" | base64 --decode 	| jq .[] | jq .[].password | sed -e 's/^"//' -e 's/"$//')
      HARBOUR_ITEM_NAME="harbour命名空间"
      APP_NAME="app名称"
      DOCKER_IMAGE_URL=$DOCKER_REGISTRY_NAME/$HARBOUR_ITEM_NAME/$APP_NAME:$IMAGE_TAG
      
      test() {
      	 branch=$BRANCH_NAME
       	./mvnw clean install
      	./mvnw sonar:sonar \
      	-Dsonar.projectKey=backend-$branch \
      	-Dsonar.projectName=backend-$branch \
      	-Dsonar.java.binaries=target/sonar \
      	-Dsonar.core.codeCoveragePlugin=jacoco
      }
      
      # 构建和上传私有仓库
      build() {
      	# packaging project with mvnw
      	chmod +x mvnw
      	./mvnw clean package -Dmaven.test.skip=true -U
      
      	# building image with docker
      	docker build -t $DOCKER_IMAGE_URL .
      	docker login --username=$DOCKER_USER --password=$DOCKER_PASSWORD $DOCKER_REGISTRY_SERVER
      	docker push $DOCKER_IMAGE_URL
      	docker rmi $DOCKER_IMAGE_URL
      }
      # 部署给测试人员使用
      deploy() {
      
      	# 使用k8s拉取镜像并部署
      	cat k8s/deploy.yaml.tmpl | \
      	sed 's/\$NAMESPACE'"/$NAMESPACE/g" | \
      	sed 's/\$ENV'"/$ENV/g" | \
      	sed 's/\$APP_NAME'"/$APP_NAME/g" | \
      	sed 's/\$DOCKER_REGISTRY_NAME'"/$DOCKER_REGISTRY_NAME/g" | \
      	sed 's/\$HARBOUR_ITEM_NAME'"/$HARBOUR_ITEM_NAME/g" | \
      	sed 's/\$IMAGE_TAG'"/$IMAGE_TAG/g" | \
      	sed 's/\$SPRING_PROFILES_ACTIVE'"/$SPRING_PROFILES_ACTIVE/g" | \
      	kubectl apply -n $NAMESPACE -f - || true
      
      	cat k8s/service.yaml.tmpl | \
      	sed 's/\$NAMESPACE'"/$NAMESPACE/g" | \
      	sed 's/\$ENV'"/$ENV/g" | \
      	sed 's/\$APP_NAME'"/$APP_NAME/g" | \
      	sed 's/\$NODE_PORT'"/$NODE_PORT/g" | \
      	kubectl apply -n $NAMESPACE -f - || true
      }
      
      
      case $1 in
      build | deploy | test)
      $1
      ;;
      *)
      echo "not support!!! example: go <build|deploy|test>"
      exit 1
      ;;
      esac
      
    • Dockerfile对应的内容为

      FROM openjdk:8u181-jre-slim
      
      COPY /target/*.jar /app.jar
      
      ENV LANG C.UTF-8
      ENV SERVER_PORT 8080
      RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
      RUN echo 'Asia/Shanghai' >/etc/timezone
      
      ENTRYPOINT ["java","-jar","/app.jar"]
      
    • k8s对应的内容为

      apiVersion: v1
      kind: Service
      metadata:
        namespace: $NAMESPACE
        name: $APP_NAME
      labels:
        app: $APP_NAME
        env: $ENV
      spec:
        ports:
        - name: $APP_NAME
          port: 8080
          protocol: TCP
          targetPort: 8080
          nodePort: $NODE_PORT
        selector:
          app: $APP_NAME
          env: $ENV
        type: NodePort
      --- 
      apiVersion: extensions/v1beta1
      kind: Deployment
      metadata:
        namespace: $NAMESPACE
        annotations:
          deployment.kubernetes.io/revision: "1"
        labels:
          app: $APP_NAME
        name: $APP_NAME
      spec:
        progressDeadlineSeconds: 600
        replicas: 3
        revisionHistoryLimit: 0
        selector:
          matchLabels:
            app: $APP_NAME
           env: $ENV
        strategy:
          type: RollingUpdate
          rollingUpdate:
           maxSurge: 1
            maxUnavailable: 2
        template:
          metadata:
           labels:
              app: $APP_NAME
              env: $ENV
          spec:
            imagePullSecrets:
           - name: regcred
      
          containers:
           - image: $DOCKER_REGISTRY_NAME/$HARBOUR_ITEM_NAME/$APP_NAME:$IMAGE_TAG
            ports:
             - containerPort: 8080
              name: web
            env:
                - name: SPRING_PROFILES_ACTIVE
                  value: $SPRING_PROFILES_ACTIVE
              imagePullPolicy: Always
              resources:
                limits:
                  cpu: 2
                  memory: 4Gi
                requests:
                  cpu: 1
                  memory: 4Gi
              name: $APP_NAME
              readinessProbe:
                httpGet:
                  path: /doc.html
                  port: 8080
                initialDelaySeconds: 60
                periodSeconds: 2
                failureThreshold: 5
      

END 转载请标明来源

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐