Kubernetes學習之路(十)之資源清單定義


一、Kubernetes常用資源

以下列舉的內容都是 kubernetes 中的 Object,這些對象都可以在 yaml 文件中作為一種 API 類型來配置。

類別 名稱
工作負載型資源對象 Pod  Replicaset  ReplicationController  Deployments StatefulSets Daemonset Job CronJob
服務發現及負載均衡  Service  Ingress
配置與存儲 Volume、Persistent Volume、CSl 、 configmap、  secret
集群資源 Namespace Node Role ClusterRole  RoleBinding  ClusterRoleBinding
元數據資源 HPA PodTemplate LimitRang

二、理解Kubernetes中的對象

在 Kubernetes 系統中,Kubernetes 對象 是持久化的條目。Kubernetes 使用這些條目去表示整個集群的狀態。特別地,它們描述了如下信息:

  • 什么容器化應用在運行(以及在哪個 Node 上)
  • 可以被應用使用的資源
  • 關於應用如何表現的策略,比如重啟策略、升級策略,以及容錯策略

Kubernetes 對象是 “目標性記錄” —— 一旦創建對象,Kubernetes 系統將持續工作以確保對象存在。通過創建對象,可以有效地告知 Kubernetes 系統,所需要的集群工作負載看起來是什么樣子的,這就是 Kubernetes 集群的 期望狀態。

與 Kubernetes 對象工作 —— 是否創建、修改,或者刪除 —— 需要使用 Kubernetes API。當使用 kubectl 命令行接口時,比如,CLI 會使用必要的 Kubernetes API 調用,也可以在程序中直接使用 Kubernetes API。

三、對象的Spec和狀態

每個 Kubernetes 對象包含兩個嵌套的對象字段,它們負責管理對象的配置:對象 spec 和 對象 statusspec 必須提供,它描述了對象的 期望狀態—— 希望對象所具有的特征。status 描述了對象的 實際狀態,它是由 Kubernetes 系統提供和更新。在任何時刻,Kubernetes 控制平面一直處於活躍狀態,管理着對象的實際狀態以與我們所期望的狀態相匹配。

例如,Kubernetes Deployment 對象能夠表示運行在集群中的應用。當創建 Deployment 時,可能需要設置 Deployment 的 spec,以指定該應用需要有 3 個副本在運行。Kubernetes 系統讀取 Deployment spec,啟動我們所期望的該應用的 3 個實例 —— 更新狀態以與 spec 相匹配。如果那些實例中有失敗的(一種狀態變更),Kubernetes 系統通過修正來響應 spec 和狀態之間的不一致 —— 這種情況,啟動一個新的實例來替換。

四、Pod的配置格式

當創建 Kubernetes 對象時,必須提供對象的 spec,用來描述該對象的期望狀態,以及關於對象的一些基本信息(例如,名稱)。當使用 Kubernetes API 創建對象時(或者直接創建,或者基於kubectl),API 請求必須在請求體中包含 JSON 格式的信息。更常用的是,需要在 .yaml 文件中為 kubectl 提供這些信息。 kubectl 在執行 API 請求時,將這些信息轉換成 JSON 格式。查看已經部署好的pod的資源定義格式:

[root@k8s-master ~]# kubectl get pod myapp-848b5b879b-5f69p -o yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: 2018-08-24T07:40:57Z
  generateName: myapp-848b5b879b-
  labels:
    pod-template-hash: "4046164356"
    run: myapp
  name: myapp-848b5b879b-5f69p
  namespace: default
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: myapp-848b5b879b
    uid: caf2ec54-a76f-11e8-84d2-000c2972dc1f
  resourceVersion: "90507"
  selfLink: /api/v1/namespaces/default/pods/myapp-848b5b879b-5f69p
  uid: 09bc0ba1-a771-11e8-84d2-000c2972dc1f
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-j5pf5
      readOnly: true
  dnsPolicy: ClusterFirst
  nodeName: k8s-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-j5pf5
    secret:
      defaultMode: 420
      secretName: default-token-j5pf5
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: 2018-08-24T07:40:57Z
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: 2018-08-24T07:40:59Z
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: null
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: 2018-08-24T07:40:57Z
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://a5e7004f45b1ec4a4297e50db6d0b5b11573e36ed8de814ea8b6cdacd13b8f9a
    image: ikubernetes/myapp:v1
    imageID: docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513
    lastState: {}
    name: myapp
    ready: true
    restartCount: 0
    state:
      running:
        startedAt: 2018-08-24T07:40:58Z
  hostIP: 192.168.56.12
  phase: Running
  podIP: 10.244.1.11
  qosClass: BestEffort
  startTime: 2018-08-24T07:40:57Z
View Code

創建資源的方法:

  • apiserver在定義資源時,僅接收JSON格式的資源定義;
  • yaml格式提供配置清單,apiservere可自動將其轉為json格式,而后再提交;

大部分資源的配置清單格式都由5個一級字段組成:

 apiVersion: group/version  指明api資源屬於哪個群組和版本,同一個組可以有多個版本
        $ kubectl api-versions

    kind: 資源類別,標記創建的資源類型,k8s主要支持以下資源類別
        Pod,ReplicaSet,Deployment,StatefulSet,DaemonSet,Job,Cronjob
    
    metadata:元數據,主要提供以下字段
        name:同一類別下的name是唯一的
        namespace:對應的對象屬於哪個名稱空間
        labels:標簽,每一個資源都可以有標簽,標簽是一種鍵值數據
        annotations:資源注解
        
        每個的資源引用方式(selflink):
            /api/GROUP/VERSION/namespace/NAMESPACE/TYPE/NAME
    
    spec: 定義目標資源的期望狀態(disired state),資源對象中最重要的字段
    
    status: 顯示資源的當前狀態(current state),本字段由kubernetes進行維護

K8s存在內嵌的格式說明,可以使用kubectl explain 進行查看,如查看Pod這個資源的定義:

[root@k8s-master ~]# kubectl explain 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
View Code

從上面可以看到apiVersion,kind等定義的鍵值都是<string>,而metadata和spec看到是一個<Object>,當看到存在<Object>的提示,說明該字段可以存在多個二級字段,那么可以使用如下命令繼續查看二級字段的定義方式:

[root@k8s-master ~]# kubectl explain pods.metadata
[root@k8s-master ~]# kubectl explain pods.spec

二級字段下,每一種字段都有對應的鍵值類型,常用類型大致如下:

<[]string>:表示是一個字串列表,也就是字串類型的數組

<Object>:表示是可以嵌套的字段

<map[string]string>:表示是一個由鍵值組成映射

<[]Object>:表示是一個對象列表

<[]Object> -required-:required表示該字段是一個必選的字段

五、使用配置清單創建自主式Pod資源 

[root@k8s-master ~]# mkdir mainfests
[root@k8s-master ~]# cd mainfrests
[root@k8s-master mainfrests]# vim pod-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: default
  labels:
    app: myapp
    tier: frontend
spec:
  containers:
  - name:myapp
    image: ikubernetes/myapp:v1
  - name: busybox
    image: busybox:latest
    command:
    - "/bin/sh"
    - "-c"
    - "sleep 3600"
[root@k8s-master mainfrests]# kubectl create -f pod-demo.yaml
[root@k8s-master mainfrests]# kubectl get pods
[root@k8s-master mainfrests]# kubectl describe pods pod-demo  #獲取pod詳細信息
[root@k8s-master mainfrests]# kubectl logs pod-demo myapp
[root@k8s-master mainfrests]# kubectl exec -it pod-demo  -c myapp -- /bin/sh

六、Pod資源下spec的containers必需字段解析

[root@k8s-master ~]# kubectl explain pods.spec.containers

name    <string> -required-    #containers 的名字
image    <string>  #鏡像地址
imagePullPolicy    <string>  #如果標簽是latest  就是Always(總是下載鏡像)  IfNotPresent(先看本地是否有此鏡像,如果沒有就下載) Never (就是使用本地鏡像)

ports    <[]Object>  #是給對象列表  可以暴露多個端口  可以對每個端口的屬性定義 例如:(名稱(可后期調用)端口號  協議  暴露在的地址上) 暴露端口只是提供額外信息的,不能限制系統是否真的暴露

   - containerPort 容器端口

     hostIP  主機地址(基本不會使用)

     hostPort 節點端口

     name 名稱

     protocol  (默認是TCP)

args  <[]string>   傳遞參數給command 相當於docker中的CMD

command    <[]string> 相當於docker中的ENTRYPOINT

如果Pod不提供commandargs使用Container,則使用Docker鏡像中的cmd或者ENTRYPOINT。

如果Pod提供command但不提供args,則僅使用提供 command的。將忽略Docker鏡像中定義EntryPoint和Cmd。

如果Pod中僅提供args,則args將作為參數提供給Docker鏡像中EntryPoint。

如果提供了commandargs,則Docker鏡像中的ENTRYPOINT和CMD都將不會生效,Pod中的args將作為參數給command運行

七、標簽及標簽選擇器 

1、標簽

key=value

  • key:只能使用 字母 數字  _  -  . (只能以字母數字開頭,不能超過63給字符)
  • value: 可以為空 只能使用 字母 數字開頭
[root@k8s-master mainfests]# kubectl get pods --show-labels  #查看pod標簽
NAME       READY     STATUS    RESTARTS   AGE       LABELS
pod-demo   2/2       Running   0          25s       app=myapp,tier=frontend
[root@k8s
-master mainfests]# kubectl get pods -l app  #過濾包含app的標簽 NAME READY STATUS RESTARTS AGE pod-demo 2/2 Running 0 1m [root@k8s-master mainfests]# kubectl get pods -L app NAME READY STATUS RESTARTS AGE APP pod-demo 2/2 Running 0 1m myapp
[root@k8s
-master mainfests]# kubectl label pods pod-demo release=canary  #給pod-demo打上標簽 pod/pod-demo labeled [root@k8s-master mainfests]# kubectl get pods -l app --show-labels NAME READY STATUS RESTARTS AGE LABELS pod-demo 2/2 Running 0 1m app=myapp,release=canary,tier=frontend
[root@k8s
-master mainfests]# kubectl label pods pod-demo release=stable --overwrite  #修改標簽 pod/pod-demo labeled [root@k8s-master mainfests]# kubectl get pods -l release NAME READY STATUS RESTARTS AGE pod-demo 2/2 Running 0 2m [root@k8s-master mainfests]# kubectl get pods -l release,app NAME READY STATUS RESTARTS AGE pod-demo 2/2 Running 0 2m

2、標簽選擇器

  • 等值關系標簽選擇器:=, == , !=  (kubectl get pods -l app=test,app=dev)
  • 集合關系標簽選擇器: KEY in (v1,v2,v3), KEY notin (v1,v2,v3)   !KEY (kubectl get pods -l "app in (test,dev)")

許多資源支持內嵌字段

  • matchLabels: 直接給定建值
  • matchExpressions: 基於給定的表達式來定義使用標簽選擇器,{key:"KEY",operator:"OPERATOR",values:[V1,V2,....]}
  • 操作符: in notin:Values字段的值必須是非空列表  Exists NotExists:  Values字段的值必須是空列表

3、節點標簽選擇器

[root@k8s-master mainfests]# kubectl explain pod.spec
   nodeName    <string>
     NodeName is a request to schedule this pod onto a specific node. If it is
     non-empty, the scheduler simply schedules this pod onto that node, assuming
     that it fits resource requirements.

   nodeSelector    <map[string]string>
     NodeSelector is a selector which must be true for the pod to fit on a node.
     Selector which must match a node's labels for the pod to be scheduled on
     that node. More info:
     https://kubernetes.io/docs/concepts/configuration/assign-pod-node/

nodeSelector可以限定pod創建在哪個節點上,舉個例子,給節點k8s-node01打上標簽disktype=ssd,讓pod-demo指定創建在k8s-node01上

(1)給k8s-node01節點打標簽
[root@k8s-master mainfests]# kubectl label nodes k8s-node01 disktype=ssd node/k8s-node01 labeled [root@k8s-master mainfests]# kubectl get nodes --show-labels NAME STATUS ROLES AGE VERSION LABELS k8s-master Ready master 10d v1.11.2 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=k8s-master,node-role.kubernetes.io/master= k8s-node01 Ready <none> 10d v1.11.2 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disktype=ssd,kubernetes.io/hostname=k8s-node01 k8s-node02 Ready <none> 9d v1.11.2 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=k8s-node02
(2)修改yaml文件,增加標簽選擇器 [root@k8s
-master mainfests]# cat pod-demo.yaml apiVersion: v1 kind: Pod metadata: name: pod-demo namespace: default labels: app: myapp tier: frontend spec: containers: - name: myapp image: ikubernetes/myapp:v1 - name: busybox image: busybox:latest command: - "/bin/sh" - "-c" - "sleep 3600" nodeSeletor: disktype: ssd
(3)重新創建pod-demo,可以看到固定調度在k8s-node01節點上 [root@k8s
-master mainfests]# kubectl delete -f pod-demo.yaml pod "pod-demo" deleted [root@k8s-master mainfests]# kubectl create -f pod-demo.yaml pod/pod-demo created [root@k8s-master mainfests]# kubectl get pods -o wide NAME READY STATUS RESTARTS AGE IP NODE pod-demo 2/2 Running 0 20s 10.244.1.13 k8s-node01 [root@k8s-master mainfests]# kubectl describe pod pod-demo ...... Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 42s default-scheduler Successfully assigned default/pod-demo to k8s-node01 ......

annotations:

  與label不同的地方在於,annotations不能用於挑選資源對象,僅用於為對象提供"元數據",沒有鍵值長度限制。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM