zoukankan      html  css  js  c++  java
  • 5、kubernetes资源清单定义入门

    使用配置清单创建资源

    定义pod时使用yaml格式

    master ~]# kubectl get pod 

    NAME                           READY   STATUS      RESTARTS   AGE
    client                         0/1     Error       0          10d
    client1                        0/1     Completed   0          9d
    client2                        0/1     Error       0          7h13m
    client3                        1/1     Running     0          5h57m
    myapp-5bc569c47d-5cdpw         1/1     Running     0          3h20m
    myapp-5bc569c47d-c4gr2         1/1     Running     0          3h20m
    myapp-5bc569c47d-njr5w         1/1     Running     0          3h20m
    nginx-deploy-55d8d67cf-hlj9v   1/1     Running     3          10d

    master ~]# kubectl get pod myapp-5bc569c47d-5cdpw -o yaml  //以yaml格式输出pod信息

    apiVersion: v1   //这里的值一般是group/version,这里省略了group名,就表示核心组
    kind: Pod    //资源类别
    metadata:   //元数据
      creationTimestamp: "2019-06-14T05:32:03Z"
      generateName: myapp-5bc569c47d-
      labels:
        pod-template-hash: 5bc569c47d
        run: myapp
      name: myapp-5bc569c47d-5cdpw
      namespace: default
      ownerReferences:
      - apiVersion: apps/v1
        blockOwnerDeletion: true
        controller: true
        kind: ReplicaSet
        name: myapp-5bc569c47d
        uid: bcd43ea4-8e43-11e9-a017-000c29cef804
      resourceVersion: "386558"
      selfLink: /api/v1/namespaces/default/pods/myapp-5bc569c47d-5cdpw
      uid: bd573709-8e65-11e9-a017-000c29cef804
    spec:    //规格,即定义接下来所要创建的资源对象所具有的特性,或者满足的规范。可以让用户定义资源对象所处的目标状态
      containers:
      - image: ikubernetes/myapp:v1
        imagePullPolicy: IfNotPresent
        name: myapp
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
          name: default-token-fckpp
          readOnly: true
      dnsPolicy: ClusterFirst
      enableServiceLinks: true
      nodeName: node01
      priority: 0
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      serviceAccount: default
      serviceAccountName: default
      terminationGracePeriodSeconds: 30
      tolerations:
      - effect: NoExecute
        key: node.kubernetes.io/not-ready
        operator: Exists
        tolerationSeconds: 300
      - effect: NoExecute
        key: node.kubernetes.io/unreachable
        operator: Exists
        tolerationSeconds: 300
      volumes:
      - name: default-token-fckpp
        secret:
          defaultMode: 420
          secretName: default-token-fckpp
    status:   //显示当前资源的当前状态,如果当前状态与目标状态不一致,则需要以目标状态为准
      conditions:
      - lastProbeTime: null
        lastTransitionTime: "2019-06-14T05:32:03Z"
        status: "True"
        type: Initialized
      - lastProbeTime: null
        lastTransitionTime: "2019-06-14T05:32:05Z"
        status: "True"
        type: Ready
      - lastProbeTime: null
        lastTransitionTime: "2019-06-14T05:32:05Z"
        status: "True"
        type: ContainersReady
      - lastProbeTime: null
        lastTransitionTime: "2019-06-14T05:32:03Z"
        status: "True"
        type: PodScheduled
      containerStatuses:
      - containerID: docker://0cc8d93c55ee79efe9d7bf4117e1c59db309be4fb498a0486317d33413066d8b
        image: ikubernetes/myapp:v1
        imageID: docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513
        lastState: {}
        name: myapp
        ready: true
        restartCount: 0
        state:
          running:
            startedAt: "2019-06-14T05:32:04Z"
      hostIP: 192.168.184.142
      phase: Running
      podIP: 10.244.3.9
      qosClass: BestEffort
      startTime: "2019-06-14T05:32:03Z"

    创建资源的方法:

    apiserver仅接收JSON格式的资源定义;

    yaml格式提供配置清单,apiserver可自动将其转为json格式,而后再提交;

    大部分资源的配置清单(5个一级字段):

    1、apiServer:group/version 指明创建的资源属于哪个api群组及其版本

    master ~]# kubectl api-versions  //查看所有版本
    admissionregistration.k8s.io/v1beta1
    apiextensions.k8s.io/v1beta1
    apiregistration.k8s.io/v1
    apiregistration.k8s.io/v1beta1
    apps/v1   //控制器deployment等属于应用程序管理的核心组资源,属于本组
    apps/v1beta1
    apps/v1beta2
    ........
    autoscaling/v1
    autoscaling/v2beta1
    autoscaling/v2beta2
    batch/v1
    batch/v1beta1
    .......
    v1   //主版本,属于核心群组,pod是最核心的资源,属于核心群组,

    alpha版:内部测试版  http://www.ttlsa.com/linux/alpha-beta-rc/

    beta版:公开测试版

    stable版:稳定版

    2、kind:资源类别,用来标记创建资源的类型,比如资源是pod或者是deployment或者service等

    3、metadata:元数据

    name

    namespace

    labels        标签

    annotations   资源注解

     

    每个资源的引用PATH

    /api/GROUP/VERSION/namespaces/NAMESPACE/TYPE/NAME   //TPYE是资源类别

    例如:selfLink: /api/v1/namespaces/default/pods/myapp-5bc569c47d-5cdpw

    4、spec:不同的资源类型,它的spec类型是不尽相同的,它是用来定义用户期望的目标状态disired state

    5、status:当前状态,current state。本字段由kubernetes集群维护,用户不能删除、定义它

    master ~]# kubectl explain pods  //pods资源如何定义

    KIND:     Pod
    VERSION:  v1
    
    DESCRIPTION:
         Pod is a collection of containers that can run on a host. This resource is
         created by clients and scheduled onto hosts.
    
    FIELDS:
       apiVersion    <string>
         APIVersion defines the versioned schema of this representation of an
         object. Servers should convert recognized schemas to the latest internal
         value, and may reject unrecognized values. More info:
         https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
    
       kind    <string>
         Kind is a string value representing the REST resource this object
         represents. Servers may infer this from the endpoint the client submits
         requests to. Cannot be updated. In CamelCase. More info:
         https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
    
       metadata    <Object>
         Standard object's metadata. More info:
         https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
    
       spec    <Object>
         Specification of the desired behavior of the pod. More info:
         https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
    
       status    <Object>
         Most recently observed status of the pod. This data may not be up to date.
         Populated by the system. Read-only. More info:
         https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status

    查看二级字段如何定义

    master ~]# kubectl explain pods.metadata

    KIND:     Pod
    VERSION:  v1
    
    RESOURCE: metadata <Object>
    
    DESCRIPTION:
         Standard object's metadata. More info:
         https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
    
         ObjectMeta is metadata that all persisted resources must have, which
         includes all objects users must create.
    
    FIELDS:
       annotations    <map[string]string>  //表示映射,由三级组成的映射,映射是另外一种json格式的数组,
         Annotations is an unstructured key value map stored with a resource that
         may be set by external tools to store and retrieve arbitrary metadata. They
         are not queryable and should be preserved when modifying objects. More
         info: http://kubernetes.io/docs/user-guide/annotations
    
       clusterName    <string>
         ......
    
       creationTimestamp    <string>     ......
    
       deletionGracePeriodSeconds    <integer>     .....
    
       deletionTimestamp    <string>
         ......
         https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
    
       finalizers    <[]string>   //前面带有[],表示是一个列表,字符串类型的数组
         Must be empty before the object is deleted from the registry. Each entry is
         an identifier for the responsible component that will remove the entry from
         the list. If the deletionTimestamp of the object is non-nil, entries in
         this list can only be removed.
    
       generateName    <string>     .....
         https://git.k8s.io/community/contributors/devel/api-conventions.md#idempotency
    
       generation    <integer>
         A sequence number representing a specific generation of the desired state.
         Populated by the system. Read-only.
    
       initializers    <Object>  //表示可以被嵌套三级字段     ....
    
       labels    <map[string]string>
         ....
    
       managedFields    <[]Object>  //是一个对象列表,一个对象由很多字段组成
         ManagedFields maps workflow-id and version to the set of fields that are
         managed by that workflow. This is mostly for internal housekeeping, and
         users typically shouldn't need to set or understand this field. A workflow
         can be the user's name, a controller's name, or the name of a specific
         apply path like "ci-cd". The set of fields is always in the version that
         the workflow used when modifying the object. This field is alpha and can be
         changed or removed without notice.
    
       name    <string>     ...... 
    
       namespace    <string>     ....
       ownerReferences    <[]Object>
         ....
    
       resourceVersion    <string>     .....
         https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency
    
       selfLink    <string>
         SelfLink is a URL representing this object. Populated by the system.
         Read-only.
    
       uid    <string>
         ....

    master ~]# kubectl explain pods.spec.containers.livenessProbe  //可以查询多级字段定义内容

    示例:基于yaml格式的配置文件,定义一个自助式pod资源

    两个容器运行在一个pod中

    [root@master ~]# mkdir manifests
    [root@master ~]# cd !$
    cd manifests
    [root@master manifests]# vim pod-demo.yaml

      1 apiVersion: v1
      2 kind: Pod
      3 metadata:
      4   name: pod-demo
      5   namespace: default
      6   labels:   //映射数据可以使用{},例如labels: {app:myapp, tier:frontend};
      7     app: myapp
      8     tier: frontend
      9 spec:
     10   containers:
     11   - name: myapp
     12     image: ikubernetes/myapp:v1
     13   - name: busybox   //由于命令错误,就将busybox删除了
     14     image: busybox:latest
     15     command:  //列表数据可以使用[],例如["/bin/sh","-c","sleep 3600"]
     16     - "/bin/sh"
     17     - "-c"
     18     - "echo $(date) >> /usr/share/nginx/html/index.html; sleep 5"   -->  由于myapp和busybox的文件系统不是同一个,所以可将此处修改为: "- sleep 3600"

    master manifests]# kubectl create -f pod-demo.yaml   //-f表示从文件中加载创建pod

    pod/pod-demo created

    master manifests]# kubectl get pods  //查看运行的pod

    NAME                           READY   STATUS      RESTARTS   AGE
    client3                        1/1     Running     0          13h
    myapp-5bc569c47d-5cdpw         1/1     Running     0          10h
    myapp-5bc569c47d-c4gr2         1/1     Running     0          10h
    myapp-5bc569c47d-njr5w         1/1     Running     0          10h
    nginx-deploy-55d8d67cf-hlj9v   1/1     Running     3          10d
    pod-demo                       1/1     Running     0          6s

    master manifests]# kubectl describe pods pod-demo //pod是类型,pod-demo是名称,先指明资源类型再指明名称,因为资源名称只在类型下唯一

    Name:               pod-demo
    Namespace:          default
    Priority:           0
    PriorityClassName:  <none>
    Node:               node03/192.168.184.144
    Start Time:         Sat, 15 Jun 2019 00:20:37 +0800
    Labels:             app=myapp
                        tier=frontend
    Annotations:        <none>
    Status:             Pending
    IP:                 10.244.1.10
    Containers:
      myapp:
        Container ID:   docker://bf8723299d620b47ddcd8073c256d057d32408d9caf46855a12876bd3c836d95
        Image:          ikubernetes/myapp:v1
        Image ID:       docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513
        Port:           <none>
        Host Port:      <none>
        State:          Running
          Started:      Sat, 15 Jun 2019 00:20:38 +0800
        Ready:          True
        Restart Count:  0
        Environment:    <none>
        Mounts:
          /var/run/secrets/kubernetes.io/serviceaccount from default-token-fckpp (ro)
      busybox:
        Container ID:  
        Image:         busybox:latest
        Image ID:      
        Port:          <none>
        Host Port:     <none>
        Command:
          /bin/sh
          -c
          echo $(date) >> /usr/share/nginx/html/index.html; sleep 5
        State:          Waiting
          Reason:       ErrImagePull
        Ready:          False
        Restart Count:  0
        Environment:    <none>
        Mounts:
          /var/run/secrets/kubernetes.io/serviceaccount from default-token-fckpp (ro)
    Conditions:
      Type              Status
      Initialized       True 
      Ready             False 
      ContainersReady   False 
      PodScheduled      True 
    Volumes:
      default-token-fckpp:
        Type:        Secret (a volume populated by a Secret)
        SecretName:  default-token-fckpp
        Optional:    false
    QoS Class:       BestEffort
    Node-Selectors:  <none>
    Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                     node.kubernetes.io/unreachable:NoExecute for 300s
    Events:
      Type     Reason     Age   From               Message
      ----     ------     ----  ----               -------
      Normal   Scheduled  96s   default-scheduler  Successfully assigned default/pod-demo to node03
      Normal   Pulled     93s   kubelet, node03    Container image "ikubernetes/myapp:v1" already present on machine
      Normal   Created    93s   kubelet, node03    Created container myapp
      Normal   Started    93s   kubelet, node03    Started container myapp
      Normal   Pulling    93s   kubelet, node03    Pulling image "busybox:latest"
      Warning  Failed     2s    kubelet, node03    Failed to pull image "busybox:latest": rpc error: code = Unknown desc = context canceled
      Warning  Failed     2s    kubelet, node03    Error: ErrImagePull
      Normal   BackOff    2s    kubelet, node03    Back-off pulling image "busybox:latest"
      Warning  Failed     2s    kubelet, node03    Error: ImagePullBackOff

    查看pod的日志

    [root@master manifests]# curl 10.244.1.10
    Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
    [root@master manifests]# kubectl logs pod-demo myapp
    10.244.0.0 - - [14/Jun/2019:16:22:29 +0000] "GET / HTTP/1.1" 200 65 "-" "curl/7.29.0" "-"
    [root@master manifests]# kubectl logs pod-demo busybox   //busybox创建容器时出现错误
    /bin/sh: can't create /usr/share/nginx/html/index.html: nonexistent directory //这里显示文件路径出现错误,因为myapp和busybox这两个容器虽然运行再同一个pod,
    但他们的文件系统是隔离的,应该在pod上创建一个存储卷,将两个容器同时挂载,这样执行的时候才能看到同一个文件。

    master manifests]# kubectl exec -it pod-demo -c myapp -- /bin/sh  //-c是指明容器名称

    / # ls
    bin    dev    etc    home   lib    media  mnt    proc   root   run    sbin   srv    sys    tmp    usr    var
    / # ls /usr/share
    GeoIP  man    misc   nginx
    / # ls /usr/share/nginx/
    html
    / # ls /usr/share/nginx/html
    50x.html    index.html
    / # cat /usr/share/nginx/html/index.html 
    Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
    / # exit

    master ~]# kubectl delete pod pod-demo  //先删除pod,进行排错
         pod "pod-demo" deleted

    master manifests]# vim pod-demo.yaml 

    15     command:
     16     - "/bin/sh"
     17     - "-c"
     18     - "sleep 3600"   //此处进行了修改

    master manifests]# kubectl create -f pod-demo.yaml
    pod/pod-demo created

    上述演示了在k8s上一个镜像运行为pod的容器,它的默认命令是如何自定义的。

    基于清单删除资源

    master manifests]# kubectl delete -f pod-demo.yaml   //表示仅删除yaml文件中所定义的资源,另外可以基于清单再次创建资源

  • 相关阅读:
    Tiny6410 交叉编译helloworld程序
    Tiny6410 设备驱动之helloworld
    Tiny6410 LED字符设备驱动
    STM32移植UCGUI3.90笔记
    USB2.0学习笔记连载(十九):EZ-USB TRM手册重要部分介绍
    USB2.0学习笔记连载(十八):keil实现寄存器的配置及相关函数讲解(二)
    USB学习笔记连载(二十):FX2LP如何实现高速和全速切换(转载)
    USB2.0学习笔记连载(十七):keil实现寄存器的配置及相关函数讲解(一)
    USB学习笔记连载(十五):USB固件更新以及安装驱动
    USB学习笔记连载(十六):USB数字签名
  • 原文地址:https://www.cnblogs.com/hanshanxiaoheshang/p/11025549.html
Copyright © 2011-2022 走看看