Kubernetes實戰總結 - DevOps實現
阿新 • • 發佈:2020-07-24
一、概述
Git:一個開源的分散式版本控制系統,可以有效、高速地處理從很小到非常大的專案版本管理。
Jenkins:一個開源軟體專案,是基於Java開發的一種持續整合工具,用於監控持續重複的工作。
Maven:專案物件模型(POM),可以通過一小段描述資訊來管理專案的構建,報告和文件的專案管理工具軟體。
Harbor:構建企業級私有Docker映象的倉庫的開源解決方案。
Kubernetes:一個開源的,用於管理雲平臺中多個主機上的容器化的應用。
二、Java映象構建
啟動指令碼run.sh:
#!/bin/sh java ${JVM_OPTS} ${JAVA_OPTS} -jar *.jar ${CLI_OPTS}2>&1 | tee -a ${OUTPUT}
構建指令碼Dockerfile:
# 基礎映象 FROM hub.jhmy.com/base/centos # 維護者 MAINTAINER leozhang # 切換目錄 WORKDIR /root # 新增環境變數 ENV JDK_VERSION=jdk1.8.0_191 ENV JAVA_HOME=/usr/local/$JDK_VERSION ENV PATH=$PATH:$JAVA_HOME/bin:$JAVA_HOME/lib/ ENV JAVA_OPTS='' CLI_OPTS='' OUTPUT='logs/output.log' ENVJVM_OPTS='-XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap -XX:MaxRAMFraction=2' # 設定時區語言 ENV TZ='Asia/Shanghai' ENV LANG='C.UTF-8' LANGUAGE='C.UTF-8' LC_ALL='C.UTF-8' # 新增程式包 ADD $JDK_VERSION.tar.gz /usr/local/ COPY run.sh . # 執行命令 RUN chmod a+x run.sh && rm -rf `ls | grep -v "^run.sh$"` && mkdir -p /root/logs # 構建映象示例 # docker build -t hub.jhmy.com/base/java:1.8 . # 啟動容器示例 # docker run -dit --name=java hub.jhmy.com/base/java:1.8
環境變數說明:
JDK_VERSION:用於指定jdk包版本(需要提前下載好jdk軟體包,且保證解壓後名稱一致)
JVM_OPTS:用於指定jvm執行引數
JAVA_OPTS:用於指定java自定義引數
CLI_OPTS:用於指定其他命令列引數
OUTPUT:用於指定服務執行日誌儲存路徑
注意:
-XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap -XX:MaxRAMFraction=2
用於jvm自動識別容器記憶體限制以及自動分配記憶體大小(jdk10版本之後則不需要設定)更多詳情>>>容器中的JVM資源該如何被安全的限制?
三、Java專案映象構建
增加專案依賴指令碼addPlugins.py:
# -*- coding:utf-8 -*- # **************************** # Author :leozhang # Date :2020/7/16 # File :addPlugins.py # Description :增加POM檔案依賴 # **************************** import os pomplug=os.environ["PLUGINS"] newpom = "" with open("pom.xml", "r+") as fp: for line in fp.readlines(): if(line.find("<build>") != -1): line += "\n" + pomplug + "\n" newpom += line with open("pom.xml", "r+") as f: f.write(newpom)print(newpom)
構建指令碼Dockerfile:
# 基礎映象 FROM hub.jhmy.com/base/java:1.8 # 維護者 MAINTAINER leozhang # 工作目錄 WORKDIR /root # 複製檔案到映象 COPY *.jar . COPY lib/ lib/ # 檢視當前目錄 RUN ls -l . # 容器啟動時執行命令 CMD ["./run.sh"] # 構建映象示例 # docker build -t hub.jhmy.com/test/appservice . # 啟動容器示例 # docker run -dit --name=appservice hub.jhmy.com/test/appservice
映象構建指令碼buildImage.sh:
#!/bin/sh # creator: leozhang # up-date: 2020/03/21 # description: buildImage.sh # 公共引數 env=$1 name=$2 tag=$3 file=$4
# 設定倉庫地址和賬戶 harbor=hub.jhmy.com username=jenkins password=$(echo Q2hpc2NkY0AxMjMK | base64 -d)
# 修改映象名稱為小寫 image=${harbor}/${env}/$(echo ${name} | tr '[A-Z]' '[a-z]') # 預設名Dockerfile if [ ! "${file}" ] ;then file=Dockerfile fi # 構建映象 echo "************* build image ***************" docker build -t ${image}:${tag} -f ${file} . echo "************* push image ***************"
# 登入倉庫 docker login -u ${username} -p ${password} https://${harbor}
# 上傳映象
docker push ${image}:${tag}
# 如果非latest標籤,則更新latest標籤映象 if [ "${tag}" != "latest" ]; then docker tag ${image}:${tag} ${image}:latest docker push ${image}:latest fi
# 登出倉庫 docker logout https://${harbor}
四、Java專案容器化部署
Deployment檔案:
apiVersion: apps/v1 # 資源版本 kind: Deployment #資源型別 metadata: #資源元資料:名稱、名稱空間等 name: appservice namespace: default spec: replicas: 3 #副本數 selector: #選擇器 matchLabels: app: appservice template: #Pod模板 metadata: #Pod元資料:標籤、註解等 labels: app: appservice annotations: version: "20200715" spec: #Pod配置:名稱、映象、拉取策略、埠等 containers: - name: appservice image: hub.jhmy.com/test/appservice:latest imagePullPolicy: Always env: #環境變數 - name: JAVA_OPTS value: "-Dprops=/root/appservice.properties -Dlogpath=/root/logs" ports: - name: dubbo containerPort: 20114 resources: #資源限制:cpu、mem limits: memory: 2Gi cpu: 1 livenessProbe: #就緒檢測&生存檢測:初始時間、超時、檢測方式等 initialDelaySeconds: 60 timeoutSeconds: 10 tcpSocket: port: 20114 readinessProbe: initialDelaySeconds: 20 timeoutSeconds: 10 tcpSocket: port: 20114 volumeMounts: #儲存掛載 - name: config mountPath: /root/appservice.properties subPath: appservice.properties - name: log mountPath: /root/logs volumes: #儲存宣告:服務配置、持久化儲存請求、本地儲存 - name: config configMap: name: appservice - name: log hostPath: path: /home/ymt/logs/appservice type: DirectoryOrCreate #affinity: #節點親和性 # nodeAffinity: # requiredDuringSchedulingIgnoredDuringExecution: # nodeSelectorTerms: # - matchExpressions: # - key: app # operator: In # values: # - appservice
ConfigMap檔案:
apiVersion: v1 kind: ConfigMap metadata: name: appservice namespace: default data: appservice.properties: |- server.port=20114
......
......
......
Service檔案:
apiVersion: v1 kind: Service metadata: name: apprestserver namespace: default spec: selector: app: apprestserver ports: - name: rest port: 20114
五、Jenkins持續部署
Pipeline任務指令碼:
def NOW = new Date().format("yyyyMMddHHmmss") def SERVER = env.JOB_BASE_NAME.toLowerCase() pipeline { agent any // parameters { // string(name: 'TAG', defaultValue: 'latest', description: '映象標籤' ) // string(name: 'BRANCH', defaultValue: 'test_0629', description: '分支名稱' ) // string(name: 'URL', defaultValue: 'http://10.88.88.226:8090/jhmy/source/wx_v1/appdataservicetemp.git', description: '專案地址' ) // string(name: 'PLUGINS', defaultValue: '<plugins> <plugin> ...... </plugin> </plugins> ', description: '相關依賴' ) // environment { ENV="test" MVN="/application/mvnBranch/bin/mvn" SCRIPT="${JENKINS_HOME}/workspace/Docker/updateConfigs/script" } stages { stage('Git Clone') { steps { git branch: '${BRANCH}', credentialsId: 'yf3b_gitlab', url: '${URL}' } } stage('Clean Package') { steps { sh "python ${SCRIPT}/addPlugins.py" sh "${MVN} clean package -Dmaven.test.skip=true" } post { success { archiveArtifacts "target/*.jar" } } } stage('Build Image') { steps { dir('target') { sh "cp ${SCRIPT}/Dockerfile-jar Dockerfile" sh "sh ${SCRIPT}/buildImage.sh ${ENV} ${SERVER} ${TAG}" } } } stage('Rolling Update') { steps { sh "kubectl config use-context k8s-ymt" sh """kubectl patch deployment ${SERVER} --patch '{"spec":{"template":{"metadata":{"annotations":{"version":"${NOW}"}}}}}'""" sh "sleep 30 && kubectl get pod -o wide | grep ${SERVER}" } } stage('Clean up') { steps { deleteDir() } } } }
作者:Leozhanggg
出處:https://www.cnblogs.com/leozhanggg/p/12069994.html
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利。