k8s的 Yaml文件编写与测试用例展示

什么是Yaml 文件?

Yaml 是一种用来写配置文件的语言。结构上它有两种可选的类型:Lists [1,2,3,4] 和 Maps {1:111}。List 用 -(破折号)来定义每一项,Map 则是一个 key:value 的键值对来表示。

Yaml文件的写法是什么样的

  1. 大小写敏感(区分大小写)
  2. 使用缩进表示层级关系
  3. 缩进时不允许使用Tab键,只允许使用空格
  4. 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  5. "#"表示注释,从这个字符一直到行尾,都会被解析器忽略
  6. “—” 为可选的分隔符(三个横线,一般我们会把配置svc和deployment写在一起)

Yaml的结构图解

在Kubernetes中,Yaml支持两种结构类型即可:Lists、Maps

在这里插入图片描述
在这里插入图片描述

Yaml文件看起来难但是转换成常见格式之后你就会熟悉

  1. Yaml 转 Properties https://www.toyaml.com/index.html
  2. Yaml 转 Json http://nodeca.github.io/js-yaml/

Kubernetes通过Yaml创建资源

如果需要通过yaml 文件创建Kubernetes 对象,需要配置如下的字段:

apiVersion - 创建该对象所使用的 Kubernetes API 的版本
kind - 想要创建的对象的资源类型
metadata - 帮助识别对象唯一性的数据,包括一个 name 字符串、UID 和可选的 namespace

案例一: Kubernetes pod编排文件讲解

  • Pod在程序中运行的必须的编排文件
apiVersion: v1 #指定api版本,此值必须在kubectl apiversion中   
kind: Pod #指定创建资源的角色/类型  
metadata: #资源的元数据/属性   
  name: test-pod #资源的名字,在同一个namespace中必须唯一   
  labels: #设定资源的标签 
    k8s-app: apache   
    version: v1   
  annotations:            #自定义注解列表   
    - name: String        #自定义注解名字   
spec: #specification of the resource content 指定该资源的内容   
  restartPolicy: Always #表明该容器一直运行,默认k8s的策略,在此容器退出后,会立即创建一个相同的容器   
  nodeSelector:     #节点选择,先给主机打标签kubectl label nodes kube-node1 zone=node1   
    zone: node1   
  containers:   
  - name: test-pod #容器的名字   
    image: 10.192.21.18:5000/test/chat:latest #容器使用的镜像地址   
    imagePullPolicy: Never # Kubernetes 拉取镜像策略
    command: ['sh'] #启动容器的运行命令,将覆盖容器中的Entrypoint,对应Dockefile中的ENTRYPOINT   
    args: ["$(str)"] #启动容器的命令参数,对应Dockerfile中CMD参数   
    env: #指定容器中的环境变量   
    - name: str #变量的名字   
      value: "/etc/run.sh" #变量的值   
    resources: #资源管理 
      requests: #容器运行时,最低资源需求,也就是说最少需要多少资源容器才能正常运行   
        cpu: 0.1 #CPU资源(核数),两种方式,浮点数或者是整数+m,0.1=100m,最少值为0.001核(1m) 
        memory: 32Mi #内存使用量   
      limits: #资源限制   
        cpu: 0.5   
        memory: 1000Mi   
    ports:   
    - containerPort: 80 #容器开放对外的端口 
      name: httpd  #名称 
      protocol: TCP   
    livenessProbe: #pod内容器健康检查的设置 
      httpGet: #通过httpget检查健康,返回200-399之间,则认为容器正常   
        path: / #URI地址   
        port: 80     
        scheme: HTTP   
      initialDelaySeconds: 180 #表明第一次检测在容器启动后多长时间后开始   
      timeoutSeconds: 5 #检测的超时时间   
      periodSeconds: 15  #检查间隔时间   
      #也可以用这种方法   
      #exec: 执行命令的方法进行监测,如果其退出码不为0,则认为容器正常   
      #  command:   
      #    - cat   
      #    - /tmp/health   
      #也可以用这种方法   
      #tcpSocket: //通过tcpSocket检查健康    
      #  port: number    
    lifecycle: #生命周期管理   
      postStart: #容器运行之前运行的任务   
        exec:   
          command:   
            - 'sh'   
            - 'yum upgrade -y'   
      preStop:#容器关闭之前运行的任务   
        exec:   
          command: ['service httpd stop']   
    volumeMounts:  #挂载持久存储卷 
    - name: volume #挂载设备的名字,与volumes[*].name 需要对应     
      mountPath: /data #挂载到容器的某个路径下   
      readOnly: True   
  volumes: #定义一组挂载设备   
  - name: volume #定义一个挂载设备的名字   
    #meptyDir: {}   
    hostPath:   
      path: /opt #挂载设备类型为hostPath,路径为宿主机下的/opt,这里设备类型支持很多种 
    #nfs

Pod属性值速查表

属性名称取值类型是否必选取值说明
versionStringRequired(必)版本号,例如v1
kindStringRequiredpod (资源类型)
metadataObjectRequired元数据
metadata.nameStringRequiredpod的名称,命名规范须符合RFC 1035规范
metadata.namespaceStringRequiredpod的所属命名空间,默认值为default
metadata.labels[]List自定义标签列表
metadata.annotation[]List自定义注解列表
SpecObjectRequiredpod中容器的详细定义
spec.containers[]ListRequiredPod容器列表
spec.containers[].nameStringRequired容器名称
spec.containers[].imageStringRequired容器镜像名称
spec.containers[].imagePullPolicyString获取镜像策略,可选值包括:Always、Never、IfNOtPresent,默认值为Always
Always:表示每次都尝试重新下载镜像
IfNotPresent:表示如果本地有镜像,使用本地镜像,本地镜像不存在时下载镜像
Never:表示仅使用本地镜像
spec.containers[].command[]List容器启动命令列表,如果不指定,则使用镜像打包是的启动命令
spec.containers[].args[]List容器启动命令参数列表
spec.containers[].workingDirString容器工作目录
spec.containers[].volumeMounts[]List挂载到容器内部的存储卷配置
spec.containers[].volumeMounts[].nameString引用Pod定义的共享存储名称,需要使用volumes[]部分定义的共享存储名称
spec.containers[].volumeMounts[].mountPathString存储卷在容器内Mount的绝对路径,应少于512字符
spec.containers[].volumeMounts[].readOnlystring是否为只读模式,默认读写模式
spec.containers[].ports[]list容器需要暴露端口号列表
spec.containers[].ports[].nameString端口名称
spec.containers[].ports[].containerPortlnt容器需要监听的端口号
spec.containers[].ports[].hostPortInt容器所在主机需要监听的端口号,默认与containerPort相同。设置hostPost时,同一台主机无法启动该容器的第二个副本
spec.containers[].ports[].protocolString端口协议,支持TCP和UDP,默认TCP
spec.containers[].env[]list容器运行前需要设置的环境变量列表
spec.containers[].env[].nameString环境变量的名称
spec.containers[].env[].valueString环境变量值
spec.containers[].resourcesObject资源限制和资源请求的请求设置
spec.containers[].resources.limitsObject资源限定的设置
spec.containers[].resources.limits.cpuStringCPU限制,单位为core数,将用于 docker run --cpu-shares参数
spec.containers[].resources.limits.memoryString内存限制,单位为MIB/GiB等,将用于docker run --memory参数
spec.containers[].resources.requestsObject容器初始化的资源限制设置
spec.containers[].resources.requests.cpuStringCPU请求,单位为core数,容器启动时初始化可用数量
spec.containers[].resources.requests.memoryString内存请求,单位为MIB、GiB容器启动的初始化可用数量
spec.volumes[]list在该Pod定义共享存储列表
spec.volumes[].nameString共享存储卷的名称;在同一个Pod中每个存储卷定义一个名称,应符合RFC 1035规范。容器定义部分的containers[].
volumeMount[].name将引用该存储卷法人名称
spec.volumes[].emptyDirObject类型为emptyDir的存储卷,表示与pod同生命周期的一个临时目录,其值为一个空对象:emptyDir
spec.volumes[].hostPath.pathString类型为hostpash的存储卷,表示挂着pod所在宿主机的目录
spec.volumes[].secretObject类型为secret的存储卷,表示挂载集群预定义的secret对象到容器内部
spec.volumes[].configMapObject类型为configMap的存储卷,表示挂载集群预定义的configMap对象到容器内部
spec.volumes[].livenessProbeObject对pod内容器设置健康状态检查的设置,当探测几次无响应后,系统自动重启该容器。可以设置的方法包括:exec、httpGet、
和tcpSocket。对一个容器仅设置一种健康检查方法
spec.volumes[].livenessProbe.execObject对pod内部健康状态检查设置exec方式
spec.volumes[].livenessProbe.exec.command[]Stringexec 需要指定的命令或者脚本
spec.volumes[].livenessProbe.httpGetObject对Pod内个容器健康状态检查,设置HTTPGet方式。需要指定Path、pod
spec.volumes[].livenessProbe.tcpSocketObject对pod内各个容器健康检查的设置,tcpSocket方式
spec.volumes[].livenessProbe.initialDelaySecondsNumber容器启动完成后进行首次探测的时间,单位为s
spec.volumes[].livenessProbe.timeoutSecondsNumber对容器健康状态检查的等待响应的超时时间。单位为s,默认为1s,超过该超时时间设置,将认为该容器不健康,将重启容器
spec.volumes[].livenessProbe.periodSecondsNumber对容器健康检查的定期时间设置,单位为s默认为10s探测一次
spec.restartPolicyStringpod的重启策略,可选值为Always、OnFailure、默认值Always
OnFailure:只有pod以非零状态终止时,kubelet才会重启容器,如果正常退出则不会重启
Always:pod一旦停止运行,则无论容器是如何终止的。kubelet都将它重启
Never:pod终止后将该pod退出吗;报告给Master,不会再重启pod
spec.nodeSelectorObject设置NodeSelector表示将该pod调度到包含这些label的Node上。以key:value格式指定
spec.imagePullSecretObjectpull镜像时使用secret名称,以name:secretkey.格式指定
spec.hostNetworkBoolean是否使用主机网络模式,默认值为false.。如果设置为true,则表示容器使用宿主机网络,使用Docker网桥,该pod将无法在同一台主机启动第二个副本

案例二: Kubernetes deployment运行

apiVersion: apps/v1   # 1.9.0 之前的版本使用 apps/v1beta2,可通过命令 kubectl api-versions 查看
kind: Deployment    #指定创建资源的角色/类型
metadata:    #资源的元数据/属性
  name: web-server    #资源的名字,在同一个namespace中必须唯一
spec:
  replicas: 2    #pod副本数量
  selector:      #定义标签选择器
    matchLabels:
      app: web-server   	#符合目标的pod的标签
  template:      			# Deployment 扩容pod 的时候根据此模板
    metadata:
      labels:    			#Pod的label
        app: web-server		#pod 副本的标签,selector 根据此标签选择pod副本
    spec:        			# 指定该资源的内容  
      containers:  		# pod内容器定义的部分
      - name: nginx      	#容器的名字  
        image: nginx:1.12.1   #容器的镜像地址    
        ports:  
        - containerPort: 80  #容器暴露的端口
  • 部署
[root@master ~]# kubectl create -f nginx.yaml

11.10.6 案例三: Kubernetes Services 运行
[root@master ~]# cat nginx-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: nginx-service		#service 名称
spec:
  selector:
    app: web-server		#匹配service 选择器标签的pod
  ports:
  - protocol: TCP
    port: 80				#service 端口
    targetPort: 80			#pod 端口

Services 属性值列表

属性名称取值类型是否必选取值说明
versionStringRequired(必)版本号,例如v1
kindStringRequiredpod (资源类型)
metadataObjectRequired元数据
metadata.nameStringRequiredService的名称,命名规范须符合RFC 1035规范
metadata.namespaceStringRequiredService的所属命名空间,默认值为default
metadata.labels[]List自定义标签列表
metadata.annotation[]List自定义注解列表
SpecObjectRequired详细描述
spec.selector: []ListRequiredLabel Selector配置,将选择具有指定Label标签的Pod作为管理范围
spec.typeStringRequiredService的类型,指定Service的访问方式,默认为ClusterIP
ClusterIP:虚拟的服务IP地址,改地址用于Kubernetes集群内部的Pod访问,在Node上kube-proxy通过设置iptables规则进行转发
LoadBalancer: 使用外接负载均衡完成到服务的负载分发,需要在spec.status.loadBalancer字段指定外部负载均衡器的IP地址, 并同时定义nodePort和clusterIP,用于公有云环境
spec.clusterIPString虚拟服务IP地址,当type=ClusterIP时,如果不指定,则系统自动分配,也可以手动指定;当type=LoaderBalancer需要指定
spec.sessionAffinityString是否支持Session,可选值为ClientIP,默认为空
spec.ports[]List需要暴露的端口列表
spec.ports[].nameString端口名称
spec.ports[].protocolString端口协议 支持tcp和udp,默认为tcp
spec.ports[].portInt服务监听的端口号
spec.ports[].targetPortInt需要转发到后端Pod的端口号
spec.ports[].nodePortInt当spec.type=NodePort时,指定映射到物理机的端口号
spec.status当spec.type=LoadBalancer时,设置外部负载均衡器的地址,用于公有云环境
spec.status.loadBalancerString外部负载均衡器
spec.status.loadBalancer.ingressString外部负载均衡器
spec.status.loadBalancer.ingress.ipString外部负载均衡器的IP地址
spec.status.loadBalancer.ingress.hostnameString外部负载均衡器的主机名

ConfigMap

ConfigMap 允许您将配置文件与属性文件分离,以使容器化的应用程序具有可移植性。

  1. Kubernetes 空间都可以使用
  2. 可以作为变量或者路径文件使用
  3. Pod支持自动更新内容
#获取系统中的ConfigMap
[root@master1 ~]# kubectl get configmap

案例:将ConfigMap中的所有键值对配置为容器环境变量

  • 将ConfigMap中的所有键值对配置为容器环境变量
root@master-1 configmap]# cat configmap-multikeys.yaml 
apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: L1
  SPECIAL_TYPE:  Nginx
  • 创建ConfigMap
[root@master-1 configmap]# kubectl apply -f   configmap-multikeys.yaml  
configmap/special-config created
  • 查看ConfigMap
[root@master-1 configmap]# kubectl get configmap/special-config -n default
NAME             DATA   AGE
special-config   2      65s
  • 查看详细内容
[root@master-1 configmap]# kubectl describe configmap special-config 
Name:         special-config
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"SPECIAL_LEVEL":"L1","SPECIAL_TYPE":"Nginx"},"kind":"ConfigMap","metadata":{"annotations":{},"name":"special-co...

Data
====
SPECIAL_TYPE:
----
Nginx
SPECIAL_LEVEL:
----
L1
Events:  <none

创建容器引用ConfigMap

[root@master-1 configmap]# cat pod-configmap.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: pod-test-configmap
spec:
  containers:
    - name: pod-test-configmap
      image: busybox
      command: [ "/bin/sh", "-c", "echo $(SPECIAL_LEVEL_KEY) $(SPECIAL_TYPE_KEY)" ]
      env:
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: SPECIAL_LEVEL
        - name: SPECIAL_TYPE_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: SPECIAL_TYPE
  restartPolicy: Never
  • 创建pod
[root@master-1 configmap]# kubectl apply -f pod-configmap.yaml     
pod/pod-test-configmap created
  • 查看pod日志
[root@master-1 configmap]# kubectl log pod-test-configmap 
log is DEPRECATED and will be removed in a future version. Use logs instead.
L1 Nginx

案例二: 将 ConfigMap 数据添加到容器中的特定路径

  • Nginx pod 文件
root@master-1 configmap]# cat nginx.yaml 
apiVersion: apps/v1beta2 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx-configmap
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx-configmap
    spec:
      containers:
      - name: nginx-configmap
        image: nginx
        volumeMounts:
          - name: config-volume
            mountPath: /mnt/
        ports:
        - containerPort: 80
      volumes:
        - name: config-volume
          configMap:
            name: special-config
            items:
            - key: SPECIAL_LEVEL
              path: keys
  • 创建
[root@master-1 configmap]# kubectl apply -f  nginx.yaml    
deployment.apps/nginx-deployment created
  • 查看容器内容
[root@master-1 configmap]# kubectl exec -i -t nginx-deployment-69fd86756f-7m2jj bash
root@nginx-deployment-69fd86756f-7m2jj:/ # cd /mnt 
root@nginx-deployment-69fd86756f-7m2jj:/mnt# cat keys 
L1root
  • 修改ConfigMap 内容(验证pod自动更新)
[root@master-1 configmap]# cat configmap-multikeys.yaml 
apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: L111
  SPECIAL_TYPE:  Nginx
  • 应用新配置
[root@master-1 configmap]# kubecel apply -f configmap-multikeys.yaml
[root@master-1 configmap]# kubectl describe configmap special-config
  • 查看容器是否可以自动更新
  • 需要等待1分钟(默认)
[root@master-1 configmap]# kubectl exec -it nginx-deployment-69fd86756f-hh6hm -- cat /mnt/keys 
L111

案例三: 将ConfigMap中的所有键值对配置为容器环境变量

  • 定义配置文件
  • 把redis 配置文件存放到configmap
  • kustomize 应用配置管理

[root@master-1 redis]# cat kustomization.yaml 
configMapGenerator:
- name: redis-master-config
  files:
  - redis-config
resources:
- redis-pod.yaml
  • 定义redis配置文件
[root@master-1 redis]# cat redis-config 
maxmemory 2mb
maxmemory-policy allkeys-lru
port 6380
  • 定义redis pod 文件
[root@master-1 redis]# cat redis-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: redis-pod
spec:
  hostNetwork: true
  containers:
  - name: redis-pod
    image: redis:5.0.4
    imagePullPolicy: IfNotPresent
    command:
      - redis-server
      - "/redis-master/redis.conf"
    env:
    - name: MASTER
      value: "true"
    ports:
    - containerPort: 6380
    resources:
      limits:
        cpu: "0.1"
    volumeMounts:
    - mountPath: /redis-master-data
      name: data
    - mountPath: /redis-master
      name: config
  volumes:
    - name: data
      emptyDir: {}
    - name: config
      configMap:
        name: redis-master-config
        items:
        - key: redis-config
          path: redis.conf
  • 创建redis
[root@master-1 redis]# kubectl apply -k .
configmap/redis-master-config-k66gtchdm4 configured
pod/ redis-pod configured
  • 获取redis节点地址
[root@master-1 redis]# kubectl get pods -o wide | grep redis
redis-pod  1/1     Running     0          6m10s   192.168.91.21   192.168.91.21   <none>           <none>
  • 连接访问redis
[root@master-19 ~]# yum install epel-release -y
[root@master-19 ~]# yum install redis -y
[root@master-19 ~]# redis-cli -h 192.168.91.21 -p 6380
192.168.91.21:6380> CONFIG GET maxmemory

1) "maxmemory"
2) "2097152" #字节
192.168.91.21:6380> CONFIG GET maxmemory-policy
1) "maxmemory-policy"
2) "allkeys-lru"
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值