k8s - Volume 简介和HostPath的使用

2024-09-02 12:36

本文主要是介绍k8s - Volume 简介和HostPath的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述

K8S 的持久化

K8S 实现持久化存储的方法有很多种
例如 卷 (Volume), 持久卷(PV), 临时卷(EV) 等, 还有很多不常用的选项上图没有列出来

其中Volume 本身也分很多种
包括

Secret, configMap(之前的文章covered了), hostPath, emptyDir等
本文主要focus on hostPath



HostPath 的简介

官方定义:
hostPath 卷能将主机节点文件系统上的文件或目录挂载到你的 Pod 中。 虽然这不是大多数 Pod 需要的,但是它为一些应用提供了强大的逃生舱。

简单来讲就是让k8s node 的目录or 文件map在你的POD 容器里
至于为什么上面提到的逃生舱, 是因为假如你的POD 崩溃了or 被shutdown, 我们仍然可以在node对应的path上找到我们想要的数据(前提是把相应的数据output 到hostpath)

但是 官方并不推荐使用hostpath 把数据输出到node上
建议用local PersisentVolume代替, 主要是安全风险的原因

原因:
如果你通过准入时的验证来限制对节点上特定目录的访问,这种限制只有在你额外要求所有 hostPath 卷的挂载都是只读的情况下才有效。如果你允许不受信任的 Pod 以读写方式挂载任意主机路径, 则该 Pod 中的容器可能会破坏可读写主机挂载卷的安全性。

无论 hostPath 卷是以只读还是读写方式挂载,使用时都需要小心,这是因为:

  1. 访问主机文件系统可能会暴露特权系统凭证(例如 kubelet 的凭证)或特权 API(例如容器运行时套接字), 这些可以被用于容器逃逸或攻击集群的其他部分。
  2. 具有相同配置的 Pod(例如基于 PodTemplate 创建的 Pod)可能会由于节点上的文件不同而在不同节点上表现出不同的行为。
  3. hostPath 卷的用量不会被视为临时存储用量。 你需要自己监控磁盘使用情况,因为过多的 hostPath 磁盘使用量会导致节点上的磁盘压力。



HostPath 的类型

除了必需的 path 属性外,你还可以选择为 hostPath 卷指定 type。

valuedesc
“”空字符串(默认)用于向后兼容,这意味着在安装 hostPath 卷之前不会执行任何检查。
DirectoryOrCreate如果在给定路径上什么都不存在,那么将根据需要创建空目录,权限设置为 0755,具有与 kubelet 相同的组和属主信息。
Directory在给定路径上必须存在的目录。
FileOrCreate如果在给定路径上什么都不存在,那么将在那里根据需要创建空文件,权限设置为 0644,具有与 kubelet 相同的组和所有权。
File在给定路径上必须存在的文件。
Socket在给定路径上必须存在的 UNIX 套接字。
CharDevice(仅 Linux Node) 在给定路径上必须存在的字符设备。
BlockDevice(仅 Linux Node) 在给定路径上必须存在的块设备。



例子

这个例子是测试多个pod同时往1个hostpath 写日志


添加filter 让其可以输出api 调用日志

我们先为springboot cloud-order service 增加1个filter

@Component
@WebFilter
@Order(1)
@Slf4j
public class InfoFilter implements Filter {@Autowiredprivate String hostname;@Overridepublic void init(FilterConfig filterConfig) throws ServletException {// Initialization code}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest httpRequest = (HttpServletRequest) request;// Log the request informationlog.info("API of hostname: {} has been called, Request Method: {}, Request URI: {}, Requested from : {}",  hostname, httpRequest.getMethod(), httpRequest.getRequestURI(), httpRequest.getRemoteAddr());// You can log more information as needed// Call the next filter in the chainchain.doFilter(request, response);}@Overridepublic void destroy() {// Cleanup code}
}



为k8s-node1 加上label

这个例子测试 多个POD 同时为1个hostpath 写日志
所以为了方便测试, 需要把所有PODs 都部署在同1个node上。

所以我们要为k8s-node1 加上label

gateman@MoreFine-S500:/app/logs$ kubectl label nodes k8s-node1 cloud-order=enabled
node/k8s-node1 labeled
gateman@MoreFine-S500:/app/logs$ kubectl get nodes --show-labels
NAME         STATUS   ROLES                  AGE    VERSION   LABELS
k8s-master   Ready    control-plane,master   190d   v1.23.6   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,ingress=true,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-master,kubernetes.io/os=linux,node-role.kubernetes.io/control-plane=,node-role.kubernetes.io/master=,node.kubernetes.io/exclude-from-external-load-balancers=
k8s-node0    Ready    <none>                 190d   v1.23.6   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,ingress=true,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-node0,kubernetes.io/os=linux
k8s-node1    Ready    <none>                 190d   v1.23.6   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,cloud-order=enabled,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-node1,kubernetes.io/os=linux
k8s-node3    Ready    <none>                 169d   v1.23.6   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-node3,kubernetes.io/os=linux

可以见到, cloud-order=enabled 这个label 已经加上到了k8s-node1



在k8s-node1 提前创建1个folder

这个例子用的类型是Directory

当然如果用DirectoryOrCreate 是可以skip 这个步骤

gateman@MoreFine-S500:~/projects/coding/k8s-s/service-case/cloud-order$ gcloud compute ssh k8s-node1
WARNING: This command is using service account impersonation. All API calls will be executed as [terraform@jason-hsbc.iam.gserviceaccount.com].
WARNING: This command is using service account impersonation. All API calls will be executed as [terraform@jason-hsbc.iam.gserviceaccount.com].
No zone specified. Using zone [europe-west2-c] for instance: [k8s-node1].
External IP address was not found; defaulting to using IAP tunneling.
WARNING: To increase the performance of the tunnel, consider installing NumPy. For instructions,
please see https://cloud.google.com/iap/docs/using-tcp-forwarding#increasing_the_tcp_upload_bandwidthWARNING: This command is using service account impersonation. All API calls will be executed as [terraform@jason-hsbc.iam.gserviceaccount.com].
Warning: Permanently added 'compute.7230880099421476498' (ED25519) to the list of known hosts.
Linux k8s-node1 5.10.0-32-cloud-amd64 #1 SMP Debian 5.10.223-1 (2024-08-10) x86_64The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sat Mar  9 19:39:42 2024 from 192.168.0.35
gateman@k8s-node1:~$ sudo su -
root@k8s-node1:~# mkdir /k8s-shared
root@k8s-node1:~# cd /k8s-shared/
root@k8s-node1:/k8s-shared# ls
root@k8s-node1:/k8s-shared# mkdir logs
root@k8s-node1:/k8s-shared# ls
logs



编写deployment yaml

deployment-cloud-order-hostpath.yaml

apiVersion: apps/v1
kind: Deployment
metadata:labels: # label of this deploymentapp: cloud-order # custom definedauthor: nvd11name: deployment-cloud-order # name of this deploymentnamespace: default
spec:replicas: 3            # desired replica count, Please note that the replica Pods in a Deployment are typically distributed across multiple nodes.revisionHistoryLimit: 10 # The number of old ReplicaSets to retain to allow rollbackselector: # label of the Pod that the Deployment is managing,, it's mandatory, without it , we will get this error # error: error validating data: ValidationError(Deployment.spec.selector): missing required field "matchLabels" in io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector ..matchLabels:app: cloud-orderstrategy: # Strategy of upodatetype: RollingUpdate # RollingUpdate or RecreaterollingUpdate:maxSurge: 25% # The maximum number of Pods that can be created over the desired number of Pods during the updatemaxUnavailable: 25% # The maximum number of Pods that can be unavailable during the updatetemplate: # Pod templatemetadata:labels:app: cloud-order # label of the Pod that the Deployment is managing. must match the selector, otherwise, will get the error Invalid value: map[string]string{"app":"bq-api-xxx"}: `selector` does not match template `labels`spec: # specification of the Podcontainers:- image: europe-west2-docker.pkg.dev/jason-hsbc/my-docker-repo/cloud-order:1.1.0 # image of the containerimagePullPolicy: Alwaysname: container-cloud-ordercommand: ["bash"]args: - "-c"- |java -jar -Dserver.port=8080 app.jar --spring.profiles.active=$APP_ENVIRONMENT --logging.file.name=/app/logs/cloud-order.logenv: # set env varaibles- name: APP_ENVIRONMENT # name of the environment variablevalue: prod # value of the environment variablevolumeMounts:- name: volume-logmountPath: /app/logs/readOnly: false # read only is set to falseports:- containerPort: 8080name: cloud-ordernodeSelector:cloud-order: enabledvolumes:- name: volume-loghostPath:path: /k8s-shared/logs # the path on the host (k8s node)type: DirectoryrestartPolicy: Always # Restart policy for all containers within the PodterminationGracePeriodSeconds: 10 # The period of time in seconds given to the Pod to terminate gracefully

注意几点,

  1. 启动命令加上 --logging.file.name=/app/logs/cloud-order.log 让日志输出到指定位置
  2. 加上volume-log 这个hostpath, 映射的主机路径是 /k8s-shared/logs
  3. volumemount 那里把 volume-log mount在了 /app/logs
  4. 使用nodeSelector 让pods 都部署在1个node



部署

gateman@MoreFine-S500:~/projects/coding/k8s-s/service-case/cloud-order/volumes$ kubectl delete deployment deployment-cloud-order
deployment.apps "deployment-cloud-order" deleted
gateman@MoreFine-S500:~/projects/coding/k8s-s/service-case/cloud-order/volumes$ kubectl apply -f deployment-cloud-order-hostpath.yaml 
deployment.apps/deployment-cloud-order created
gateman@MoreFine-S500:~/projects/coding/k8s-s/service-case/cloud-order/volumes$ kubectl get pods
NAME                                         READY   STATUS      RESTARTS       AGE
deployment-bq-api-service-6f6ffc7866-8djx9   1/1     Running     3 (13d ago)    18d
deployment-bq-api-service-6f6ffc7866-g4854   1/1     Running     12 (13d ago)   61d
deployment-bq-api-service-6f6ffc7866-lwxt7   1/1     Running     14 (13d ago)   64d
deployment-bq-api-service-6f6ffc7866-mxwcq   1/1     Running     11 (13d ago)   61d
deployment-cloud-order-ff4989c97-h8ktj       1/1     Running     0              7s
deployment-cloud-order-ff4989c97-xg2x2       1/1     Running     0              7s
deployment-cloud-order-ff4989c97-zc2dq       1/1     Running     0              7s



测试

多次调用cloud-order的某个api

curl http://www.jp-gcp-vms.cloud:8085/cloud-order/actuator/info
curl http://www.jp-gcp-vms.cloud:8085/cloud-order/actuator/info
curl http://www.jp-gcp-vms.cloud:8085/cloud-order/actuator/info
curl http://www.jp-gcp-vms.cloud:8085/cloud-order/actuator/info
curl http://www.jp-gcp-vms.cloud:8085/cloud-order/actuator/info

进入k8s-node1 查看相应的日志文件:

root@k8s-node1:/k8s-shared/logs# tail -f cloud-order.log...
2024-09-01T14:28:14.298Z  INFO 1 --- [http-nio-8080-exec-1] com.home.clouduser.filter.InfoFilter     : API of hostname: deployment-cloud-order-ff4989c97-h8ktj has been called, Request Method: GET, Request URI: /actuator/info, Requested from : 192.168.0.35
2024-09-01T14:28:15.384Z  INFO 1 --- [http-nio-8080-exec-2] com.home.clouduser.filter.InfoFilter     : API of hostname: deployment-cloud-order-ff4989c97-h8ktj has been called, Request Method: GET, Request URI: /actuator/info, Requested from : 192.168.0.35
2024-09-01T14:28:15.856Z  INFO 1 --- [http-nio-8080-exec-2] com.home.clouduser.filter.InfoFilter     : API of hostname: deployment-cloud-order-ff4989c97-zc2dq has been called, Request Method: GET, Request URI: /actuator/info, Requested from : 192.168.0.35
2024-09-01T14:28:17.211Z  INFO 1 --- [http-nio-8080-exec-3] com.home.clouduser.filter.InfoFilter     : API of hostname: deployment-cloud-order-ff4989c97-h8ktj has been called, Request Method: GET, Request URI: /actuator/info, Requested from : 192.168.0.35
2024-09-01T14:28:18.183Z  INFO 1 --- [http-nio-8080-exec-4] com.home.clouduser.filter.InfoFilter     : API of hostname: deployment-cloud-order-ff4989c97-h8ktj has been called, Request Method: GET, Request URI: /actuator/info, Requested from : 192.168.0.35
2024-09-01T14:28:19.128Z  INFO 1 --- [http-nio-8080-exec-2] com.home.clouduser.filter.InfoFilter     : API of hostname: deployment-cloud-order-ff4989c97-xg2x2 has been called, Request Method: GET, Request URI: /actuator/info, Requested from : 192.168.0.35

可以见到 , 由于loadbalancer 的关系, 多个pods轮流被调用, 但是都可以写进同1个hostpath内的日志文件

所以如果用append 方式(例如写日子) 多个pod 写同1个host path 是不会由文件冲突问题的!

这篇关于k8s - Volume 简介和HostPath的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1129973

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

ASIO网络调试助手之一:简介

多年前,写过几篇《Boost.Asio C++网络编程》的学习文章,一直没机会实践。最近项目中用到了Asio,于是抽空写了个网络调试助手。 开发环境: Win10 Qt5.12.6 + Asio(standalone) + spdlog 支持协议: UDP + TCP Client + TCP Server 独立的Asio(http://www.think-async.com)只包含了头文件,不依

90、k8s之secret+configMap

一、secret配置管理 配置管理: 加密配置:保存密码,token,其他敏感信息的k8s资源 应用配置:我们需要定制化的给应用进行配置,我们需要把定制好的配置文件同步到pod当中容器 1.1、加密配置: secret: [root@master01 ~]# kubectl get secrets ##查看加密配置[root@master01 ~]# kubectl get se