K8s - SpringBoot 實現零宕機發布

前言

K8s + SpringBoot 實現零宕機發布:健康檢查 + 滾動更新 + 優雅停機 + 彈性伸縮 + Prometheus 監控 + 配置分離(鏡像複用)

配置

健康檢查

業務層面

項目依賴 pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

定義訪問端口、路徑及權限 application.yaml

management:
  server:
    port: 50000                         # 啓用獨立運維端口
  endpoint:                             # 開啓health端點
    health:
      probes:
        enabled: true
  endpoints:
    web:
      exposure:
        base-path: /actuator            # 指定上下文路徑,啓用相應端點
        include: health

將暴露/actuator/health/readiness/actuator/health/liveness兩個接口,訪問方式如下:

http://127.0.0.1:50000/actuator/health/readiness
http://127.0.0.1:50000/actuator/health/liveness
運維層面

k8s 部署模版 deployment.yaml

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
      - name: {APP_NAME}
        image: {IMAGE_URL}
        imagePullPolicy: Always
        ports:
        - containerPort: {APP_PORT}
        - name: management-port
          containerPort: 50000         # 應用管理端口
        readinessProbe:                # 就緒探針
          httpGet:
            path: /actuator/health/readiness
            port: management-port
          initialDelaySeconds: 30      # 延遲加載時間
          periodSeconds: 10            # 重試時間間隔
          timeoutSeconds: 1            # 超時時間設置
          successThreshold: 1          # 健康閾值
          failureThreshold: 6          # 不健康閾值
        livenessProbe:                 # 存活探針
          httpGet:
            path: /actuator/health/liveness
            port: management-port
          initialDelaySeconds: 30      # 延遲加載時間
          periodSeconds: 10            # 重試時間間隔
          timeoutSeconds: 1            # 超時時間設置
          successThreshold: 1          # 健康閾值
          failureThreshold: 6          # 不健康閾值

滾動更新

k8s 資源調度之滾動更新策略,若要實現零宕機發布,需支持健康檢查

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {APP_NAME}
  labels:
    app: {APP_NAME}
spec:
  selector:
    matchLabels:
      app: {APP_NAME}
  replicas: {REPLICAS}    # Pod副本數
  strategy:
    type: RollingUpdate    # 滾動更新策略
    rollingUpdate:
      maxSurge: 1                   # 升級過程中最多可以比原先設置的副本數多出的數量
      maxUnavailable: 1             # 升級過程中最多有多少個POD處於無法提供服務的狀態
優雅停機

在 K8s 中,當我們實現滾動升級之前,務必要實現應用級別的優雅停機。否則滾動升級時,還是會影響到業務。使應用關閉線程、釋放連接資源後再停止服務

業務層面

項目依賴 pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

定義訪問端口、路徑及權限 application.yaml

spring:
  application:
    name: <xxx>
  profiles:
    active: @profileActive@
  lifecycle:
    timeout-per-shutdown-phase: 30s     # 停機過程超時時長設置30s,超過30s,直接停機
server:
  port: 8080
  shutdown: graceful                    # 默認爲IMMEDIATE,表示立即關機;GRACEFUL表示優雅關機
management:
  server:
    port: 50000                         # 啓用獨立運維端口
  endpoint:                             # 開啓shutdown和health端點
    shutdown:
      enabled: true
    health:
      probes:
        enabled: true
  endpoints:
    web:
      exposure:
        base-path: /actuator            # 指定上下文路徑,啓用相應端點
        include: health,shutdown

將暴露/actuator/shutdown接口,調用方式如下:

curl -X POST 127.0.0.1:50000/actuator/shutdown
運維層面

確保 dockerfile 模版集成 curl 工具,否則無法使用 curl 命令

FROM openjdk:8-jdk-alpine
#構建參數
ARG JAR_FILE
ARG WORK_PATH="/app"
ARG EXPOSE_PORT=8080
#環境變量
ENV JAVA_OPTS=""\
    JAR_FILE=${JAR_FILE}
#設置時區
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories  \
    && apk add --no-cache curl
#將maven目錄的jar包拷貝到docker中,並命名爲for_docker.jar
COPY target/$JAR_FILE $WORK_PATH/
#設置工作目錄
WORKDIR $WORK_PATH
# 指定於外界交互的端口
EXPOSE $EXPOSE_PORT
# 配置容器,使其可執行化
ENTRYPOINT exec java $JAVA_OPTS -jar $JAR_FILE

k8s 部署模版 deployment.yaml

注:經驗證,java 項目可省略結束回調鉤子的配置

此外,若需使用回調鉤子,需保證鏡像中包含 curl 工具,且需注意應用管理端口(50000)不能暴露到公網

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
      - name: {APP_NAME}
        image: {IMAGE_URL}
        imagePullPolicy: Always
        ports:
        - containerPort: {APP_PORT}
        - containerPort: 50000
        lifecycle:
          preStop:       # 結束回調鉤子
            exec:
              command: ["curl", "-XPOST", "127.0.0.1:50000/actuator/shutdown"]

彈性伸縮

爲 pod 設置資源限制後,創建 HPA

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {APP_NAME}
  labels:
    app: {APP_NAME}
spec:
  template:
    spec:
      containers:
      - name: {APP_NAME}
        image: {IMAGE_URL}
        imagePullPolicy: Always
        resources:                     # 容器資源管理
          limits:                      # 資源限制(監控使用情況)
            cpu: 0.5
            memory: 1Gi
          requests:                    # 最小可用資源(靈活調度)
            cpu: 0.15
            memory: 300Mi
---
kind: HorizontalPodAutoscaler            # 彈性伸縮控制器
apiVersion: autoscaling/v2beta2
metadata:
  name: {APP_NAME}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {APP_NAME}
  minReplicas: {REPLICAS}                # 縮放範圍
  maxReplicas: 6
  metrics:
    - type: Resource
      resource:
        name: cpu                        # 指定資源指標
        target:
          type: Utilization
          averageUtilization: 50

Prometheus 集成

業務層面

項目依賴 pom.xml

<!-- 引入Spring boot的監控機制-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

定義訪問端口、路徑及權限 application.yaml

management:
  server:
    port: 50000                         # 啓用獨立運維端口
  metrics:
    tags:
      application: ${spring.application.name}
  endpoints:
    web:
      exposure:
        base-path: /actuator            # 指定上下文路徑,啓用相應端點
        include: metrics,prometheus

將暴露/actuator/metric/actuator/prometheus接口,訪問方式如下:

http://127.0.0.1:50000/actuator/metric
http://127.0.0.1:50000/actuator/prometheus
運維層面

deployment.yaml

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    metadata:
      annotations:
        prometheus:io/port: "50000"
        prometheus.io/path: /actuator/prometheus  # 在流水線中賦值
        prometheus.io/scrape: "true"              # 基於pod的服務發現

配置分離

方案:通過 configmap 掛載外部配置文件,並指定激活環境運行

作用:配置分離,避免敏感信息泄露;鏡像複用,提高交付效率

通過文件生成 configmap

# 通過dry-run的方式生成yaml文件
kubectl create cm -n <namespace> <APP_NAME> --from-file=application-test.yaml --dry-run=1 -oyaml > configmap.yaml
# 更新
kubectl apply -f configmap.yaml

掛載 configmap 並指定激活環境

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {APP_NAME}
  labels:
    app: {APP_NAME}
spec:
  template:
    spec:
      containers:
      - name: {APP_NAME}
        image: {IMAGE_URL}
        imagePullPolicy: Always
        env:
          - name: SPRING_PROFILES_ACTIVE   # 指定激活環境
            value: test
        volumeMounts:                      # 掛載configmap
        - name: conf
          mountPath: "/app/config"         # 與Dockerfile中工作目錄一致
          readOnly: true
      volumes:
      - name: conf
        configMap:
          name: {APP_NAME}

彙總配置

業務層面

項目依賴 pom.xml

<!-- 引入Spring boot的監控機制-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

定義訪問端口、路徑及權限 application.yaml

spring:
  application:
    name: project-sample
  profiles:
    active: @profileActive@
  lifecycle:
    timeout-per-shutdown-phase: 30s     # 停機過程超時時長設置30s,超過30s,直接停機
server:
  port: 8080
  shutdown: graceful                    # 默認爲IMMEDIATE,表示立即關機;GRACEFUL表示優雅關機
management:
  server:
    port: 50000                         # 啓用獨立運維端口
  metrics:
    tags:
      application: ${spring.application.name}
  endpoint:                             # 開啓shutdown和health端點
    shutdown:
      enabled: true
    health:
      probes:
        enabled: true
  endpoints:
    web:
      exposure:
        base-path: /actuator            # 指定上下文路徑,啓用相應端點
        include: health,shutdown,metrics,prometheus

運維層面

確保 dockerfile 模版集成 curl 工具,否則無法使用 curl 命令

FROM openjdk:8-jdk-alpine
#構建參數
ARG JAR_FILE
ARG WORK_PATH="/app"
ARG EXPOSE_PORT=8080
#環境變量
ENV JAVA_OPTS=""\
    JAR_FILE=${JAR_FILE}
#設置時區
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories  \
    && apk add --no-cache curl
#將maven目錄的jar包拷貝到docker中,並命名爲for_docker.jar
COPY target/$JAR_FILE $WORK_PATH/
#設置工作目錄
WORKDIR $WORK_PATH
# 指定於外界交互的端口
EXPOSE $EXPOSE_PORT
# 配置容器,使其可執行化
ENTRYPOINT exec java $JAVA_OPTS -jar $JAR_FILE

k8s 部署模版 deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {APP_NAME}
  labels:
    app: {APP_NAME}
spec:
  selector:
    matchLabels:
      app: {APP_NAME}
  replicas: {REPLICAS}                            # Pod副本數
  strategy:
    type: RollingUpdate                           # 滾動更新策略
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      name: {APP_NAME}
      labels:
        app: {APP_NAME}
      annotations:
        timestamp: {TIMESTAMP}
        prometheus.io/port: "50000"               # 不能動態賦值
        prometheus.io/path: /actuator/prometheus
        prometheus.io/scrape: "true"              # 基於pod的服務發現
    spec:
      affinity:                                   # 設置調度策略,採取多主機/多可用區部署
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: app
                  operator: In
                  values:
                  - {APP_NAME}
              topologyKey: "kubernetes.io/hostname" # 多可用區爲"topology.kubernetes.io/zone"
      terminationGracePeriodSeconds: 30             # 優雅終止寬限期
      containers:
      - name: {APP_NAME}
        image: {IMAGE_URL}
        imagePullPolicy: Always
        ports:
        - containerPort: {APP_PORT}
        - name: management-port
          containerPort: 50000         # 應用管理端口
        readinessProbe:                # 就緒探針
          httpGet:
            path: /actuator/health/readiness
            port: management-port
          initialDelaySeconds: 30      # 延遲加載時間
          periodSeconds: 10            # 重試時間間隔
          timeoutSeconds: 1            # 超時時間設置
          successThreshold: 1          # 健康閾值
          failureThreshold: 9          # 不健康閾值
        livenessProbe:                 # 存活探針
          httpGet:
            path: /actuator/health/liveness
            port: management-port
          initialDelaySeconds: 30      # 延遲加載時間
          periodSeconds: 10            # 重試時間間隔
          timeoutSeconds: 1            # 超時時間設置
          successThreshold: 1          # 健康閾值
          failureThreshold: 6          # 不健康閾值
        resources:                     # 容器資源管理
          limits:                      # 資源限制(監控使用情況)
            cpu: 0.5
            memory: 1Gi
          requests:                    # 最小可用資源(靈活調度)
            cpu: 0.1
            memory: 200Mi
        env:
          - name: TZ
            value: Asia/Shanghai
---
kind: HorizontalPodAutoscaler            # 彈性伸縮控制器
apiVersion: autoscaling/v2beta2
metadata:
  name: {APP_NAME}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {APP_NAME}
  minReplicas: {REPLICAS}                # 縮放範圍
  maxReplicas: 6
  metrics:
    - type: Resource
      resource:
        name: cpu                        # 指定資源指標
        target:
          type: Utilization
          averageUtilization: 50

作者:lc_1203

來源:blog.csdn.net/qq_14999375/article/details/123309636

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/rMIE9x3v3iTt7aQDNoZtoA