K8s(健康检查+滚动更新+优雅停机+弹性伸缩+Prometheus监控+配置分离)

前言

快速配置请直接跳转至汇总配置

K8s + SpringBoot实现零宕机发布:健康检查+滚动更新+优雅停机+弹性伸缩+Prometheus监控+配置分离(镜像复用)
配置
健康检查

健康检查类型:就绪探针(readiness)+ 存活探针(liveness)探针类型:exec(进入容器执行脚本)、tcpSocket(探测端口)、httpGet(调用接口)

业务层面

项目依赖 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: trueendpoints: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: Alwaysports:- containerPort: {APP_PORT}- name: management-portcontainerPort: 50000         # 应用管理端口readinessProbe:                # 就绪探针httpGet:path: /actuator/health/readinessport: management-portinitialDelaySeconds: 30      # 延迟加载时间periodSeconds: 10            # 重试时间间隔timeoutSeconds: 1            # 超时时间设置successThreshold: 1          # 健康阈值failureThreshold: 6          # 不健康阈值livenessProbe:                 # 存活探针httpGet:path: /actuator/health/livenessport: management-portinitialDelaySeconds: 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: 8080shutdown: graceful                    # 默认为IMMEDIATE,表示立即关机;GRACEFUL表示优雅关机management:server:port: 50000                         # 启用独立运维端口endpoint:                             # 开启shutdown和health端点shutdown:enabled: truehealth:probes:enabled: trueendpoints: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: Alwaysports:- containerPort: {APP_PORT}- containerPort: 50000lifecycle: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: Alwaysresources:                     # 容器资源管理limits:                      # 资源限制(监控使用情况)cpu: 0.5memory: 1Girequests:                    # 最小可用资源(灵活调度)cpu: 0.15memory: 300Mi
kind: HorizontalPodAutoscaler            # 弹性伸缩控制器
apiVersion: autoscaling/v2beta2
metadata:name: {APP_NAME}
spec:scaleTargetRef:apiVersion: apps/v1kind: Deploymentname: {APP_NAME}minReplicas: {REPLICAS}                # 缩放范围maxReplicas: 6metrics:- type: Resourceresource:name: cpu                        # 指定资源指标target:type: UtilizationaverageUtilization: 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 <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: Alwaysenv:- name: SPRING_PROFILES_ACTIVE   # 指定激活环境value: testvolumeMounts:                      # 挂载configmap- name: confmountPath: "/app/config"         # 与Dockerfile中工作目录一致readOnly: truevolumes:- name: confconfigMap: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-sampleprofiles:active: @profileActive@lifecycle:timeout-per-shutdown-phase: 30s     # 停机过程超时时长设置30s,超过30s,直接停机server:port: 8080shutdown: graceful                    # 默认为IMMEDIATE,表示立即关机;GRACEFUL表示优雅关机management:server:port: 50000                         # 启用独立运维端口metrics:tags:application: ${spring.application.name}endpoint:                             # 开启shutdown和health端点shutdown:enabled: truehealth:probes:enabled: trueendpoints: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: 1maxUnavailable: 0template:metadata:name: {APP_NAME}labels:app: {APP_NAME}annotations:timestamp: {TIMESTAMP}prometheus.io/port: "50000"               # 不能动态赋值prometheus.io/path: /actuator/prometheusprometheus.io/scrape: "true"              # 基于pod的服务发现spec:affinity:                                   # 设置调度策略,采取多主机/多可用区部署podAntiAffinity:preferredDuringSchedulingIgnoredDuringExecution:- weight: 100podAffinityTerm:labelSelector:matchExpressions:- key: appoperator: Invalues:- {APP_NAME}topologyKey: "kubernetes.io/hostname" # 多可用区为"topology.kubernetes.io/zone"terminationGracePeriodSeconds: 30             # 优雅终止宽限期containers:- name: {APP_NAME}image: {IMAGE_URL}imagePullPolicy: Alwaysports:- containerPort: {APP_PORT}- name: management-portcontainerPort: 50000         # 应用管理端口readinessProbe:                # 就绪探针httpGet:path: /actuator/health/readinessport: management-portinitialDelaySeconds: 30      # 延迟加载时间periodSeconds: 10            # 重试时间间隔timeoutSeconds: 1            # 超时时间设置successThreshold: 1          # 健康阈值failureThreshold: 9          # 不健康阈值livenessProbe:                 # 存活探针httpGet:path: /actuator/health/livenessport: management-portinitialDelaySeconds: 30      # 延迟加载时间periodSeconds: 10            # 重试时间间隔timeoutSeconds: 1            # 超时时间设置successThreshold: 1          # 健康阈值failureThreshold: 6          # 不健康阈值resources:                     # 容器资源管理limits:                      # 资源限制(监控使用情况)cpu: 0.5memory: 1Girequests:                    # 最小可用资源(灵活调度)cpu: 0.1memory: 200Mienv:- name: TZvalue: Asia/Shanghai
---
kind: HorizontalPodAutoscaler            # 弹性伸缩控制器
apiVersion: autoscaling/v2beta2
metadata:name: {APP_NAME}
spec:scaleTargetRef:apiVersion: apps/v1kind: Deploymentname: {APP_NAME}minReplicas: {REPLICAS}                # 缩放范围maxReplicas: 6metrics:- type: Resourceresource:name: cpu                        # 指定资源指标target:type: UtilizationaverageUtilization: 50

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/25204.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

D3JS教程_编程入门自学教程_菜鸟教程-免费教程分享

教程简介 D3是Data-Driven Documents的缩写&#xff0c;D3.js是一个基于数据管理文档的资源JavaScript库。 D3 是最有效的数据可视化框架之一。它允许开发人员在 HTML、CSS 和 SVG 的帮助下在浏览器中创建动态的交互式数据可视化。数据可视化是将过滤后的数据以图片和图形的形…

Ubuntu下nvidia-smi失败,使用dkms解决

Ubuntu下nvidia-smi失败&#xff0c;使用dkms解决 错误信息 nvidia-smi显示无法与驱动通讯 NVIDIA-SMI has failed because it couldnt communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.原因 一般来说是因为机器重…

useEffect中的函数会执行2次原因

一、useEffect介绍 useEffect是React18的新特性&#xff0c;表示React的生命周期Hooks组件。等价于Claas组件的componentDidMount、componentDidUpdate&#xff0c;useEffect的返回函数等价于componentWillUnmount。&#xff08;组件卸载、重新挂载都会触发这个函数&#xff0c…

【计算机网络】socket编程

文章目录 1. 网络通信的理解2.进程PID可以取代端口号吗&#xff1f;3. 认识TCP协议4. 认识 UDP协议5. socket编程接口udp_server.hpp的代码解析socket——创建 socket 文件描述符Initserver——初始化1.创建套接字接口&#xff0c;打开网络文件bind——绑定的使用 2.给服务器指…

[webpack] 基本配置 (一)

文章目录 1.基本介绍2.功能介绍3.简单使用3.1 文件目录和内容3.2 下载依赖3.3 启动webpack 4.基本配置4.1 五大核心概念4.2 基本使用 1.基本介绍 Webpack 是一个静态资源打包工具。它会以一个或多个文件作为打包的入口, 将我们整个项目所有文件编译组合成一个或多个文件输出出去…

webpack基础知识八:说说如何借助webpack来优化前端性能?

一、背景 随着前端的项目逐渐扩大&#xff0c;必然会带来的一个问题就是性能 尤其在大型复杂的项目中&#xff0c;前端业务可能因为一个小小的数据依赖&#xff0c;导致整个页面卡顿甚至奔溃 一般项目在完成后&#xff0c;会通过webpack进行打包&#xff0c;利用webpack对前…

了解Stream流

文章目录 java Stream流单列集合双列集合数组可变参数 filter什么是filter从代码中理解filter截取元素 limt()跳过指定参数个数的数据 skip()拼接 concat(流1&#xff0c;流2)去重 distinct排序 sorted升序降序 统计数据元素 count() 收集Stream流的数据ListSetMap java Stream…

医疗器械研发中的可用性工程实践(一)

致读者&#xff1a;以前看《楚门的世界》&#xff0c;《蝴蝶效应》&#xff0c;《肖申克的救赎》&#xff0c;《教父》&#xff0c;《横道世之介》&#xff0c;《老友记》&#xff0c;一个人的一生匆匆。作为平凡人就是历史大河中的浪花&#xff0c;顺势而为&#xff0c;起起伏…

spring boot 配置文件和属性注入

文章目录 配置文件位置和路径自定义配置文件 属性注入添加yaml文件的支持 配置文件 位置和路径 当我们创建一个 Spring Boot 工程时&#xff0c;默认 resources 目录下就有一个 application.properties 文件&#xff0c;可以在 application.properties 文件中进行项目配置&am…

wsl安装ziran2019

首先从windows商店搜索ubuntu18 &#xff08;亲测Ubuntu20不行&#xff09; 然后第一次打开会自动安装。 &#xff08;我是用的wsl一代&#xff0c;二代没测试过&#xff09; 新安装的系统首先要更新apt sudo apt update然后设置git git config --global https.proxy http:…

算法与数据结构(二十一)二叉树(纲领篇)

备注&#xff1a;本文旨在通过 labuladong 的二叉树&#xff08;纲领篇&#xff09;理解框架思维&#xff0c;用于个人笔记及交流学习&#xff0c;版权归原作者 labuladong 所有&#xff1b; 我刷了这么多年题&#xff0c;浓缩出二叉树算法的一个总纲放在这里&#xff0c;也许…

C++ 智能指针shared_ptr

文章目录 C智能指针shared_ptr概述shared_ptr使用方法shared_ptr引用计数的增加与减少shared_ptr常用操作 C智能指针shared_ptr概述 在介绍智能指针前先看如下代码 void func1(std::string& str) {std::string* ps new std::string(str);str *ps;return; }void func2(s…

ELK企业级日志分析系统

目录 一、ELK 概述 1.ElasticSearch 2.Kiabana 3.Logstash 可以添加的其它组件 1.Filebeat 2.Fluentd 三、为什么要使用 ELK 四、ELK 的工作原理 五、 ELK Elasticsearch 集群部署 更改主机名、配置域名解析、查看Java环境 部署 Elasticsearch 软件 修改elasticsearc…

自然语言处理从入门到应用——LangChain:提示(Prompts)-[示例选择器(Example Selectors)]

分类目录&#xff1a;《自然语言处理从入门到应用》总目录 如果我们拥有大量的示例&#xff0c;我们可能需要选择在提示中包含哪些示例。ExampleSelector是负责执行此操作的类。 其基本接口定义如下所示&#xff1a; class BaseExampleSelector(ABC):"""Interf…

爬虫获取电影数据----以沈腾参演电影为例

数据可视化&分析实战 1.1 沈腾参演电影数据获取 文章目录 数据可视化&分析实战前言1. 网页分析2. 构建数据获取函数2.1 网页数据获取函数2.2 网页照片获取函数 3. 获取参演影视作品基本数据4. 电影详细数据获取4.1 导演、演员、描述、类型、投票人数、评分信息、电影海…

Wisej.NET Crack,Wisej.NET的核心功能

Wisej.NET Crack&#xff0c;Wisej.NET的核心功能 Wisej.NET是一个跨平台的web框架&#xff0c;用于使用.NET和C#/VB.NET而不是HTML和JavaScript构建现代HTML5应用程序。它包含创建任务关键型web应用程序所需的一切&#xff0c;包括UI组件、会话处理、状态管理和后端集成。借助…

单元测试之 - Spring框架提供的单元/集成测试注解

Spring框架提供了很多注解来辅助完成单元测试和集成测试(备注&#xff1a;这里的集成测试指容器内部的集成测试&#xff0c;非系统间的集成测试)&#xff0c;先看看Spring框架提供了哪些注解以及对应的作用。RunWith(SpringRunner.class) / ExtendWith(SpringExtension.class)&…

设计模式行为型——备忘录模式

目录 什么是备忘录模式 备忘录模式的实现 备忘录模式角色 备忘录模式类图 备忘录模式举例 备忘录模式代码实现 备忘录模式的特点 优点 缺点 使用场景 注意事项 实际应用 什么是备忘录模式 备忘录模式&#xff08;Memento Pattern&#xff09;又叫做快照模式&#x…

高并发负载均衡---LVS

目录 前言 一&#xff1a;负载均衡概述 二&#xff1a;为啥负载均衡服务器这么快呢&#xff1f; ​编辑 2.1 七层应用程序慢的原因 2.2 四层负载均衡器LVS快的原因 三&#xff1a;LVS负载均衡器的三种模式 3.1 NAT模式 3.1.1 什么是NAT模式 3.1.2 NAT模式实现LVS的缺点…

openwr折腾记7-Frpc使用自主域名解析透传本地服务免费不断线的探索

Frpc使用自主域名解析透传本地服务 综述frp透传http服务结构流程 第一部分openwrt-frpc客户端配置和使用指定服务器指定规则在自己的域名运营商处添加域名解析 第二部分shell编码实现frp自由切换服务器并更新dns解析获取切换服务器参数脚本实现切换脚本更新DNS解析打开openwrt计…