一文看懂k8s Deployment yaml


本文適合新手剛接觸kubernetes,講解部署(Deployment) yaml的字段。

部署(Deployment)是k8s中常用的資源之一,部署是無狀態的,為一般性項目應用的主體,我們可以像聲明docker-compose.yaml文件一樣去定義容器的屬性。

k8s資源管理的方式

k8s有兩種方式來管理對象:

  • 命令式,即通過Kubectl指令直接操作對象。
  • 聲明式,通過定義資源yaml來操作對象。

兩者背后最終都是通過請求k8s-apiserver實現交互。
相比命令式,聲明式更具有完整性、靈活性、可維護性和擴展性。

YAML 基礎

YAML是一個JSON的超集,意味着任何有效JSON文件也都是一個有效的YAML文件。
k8s上只需要掌握YAML的兩種結構類型:

  • Lists
  • Maps

List 用 -(破折號) 來定義每一項;Map 則是一個 key:value 的鍵值對來表示。

k8s上的yaml語法規則

大小寫敏感
使用縮進表示層級關系
縮進時不允許使用Tal鍵,只允許使用空格
縮進的空格數目不重要,只要相同層級的元素左側對齊即可
"#"表示注釋,從這個字符一直到行尾,都會被解析器忽略 
"---"" 為可選的分隔符

Deployment yaml常見字段解析

apiVersion: v1       #必填,版本號,例如v1
kind: Depolyment     #必填
metadata:       #必填,元數據
  name: string       #必填,Pod名稱
  namespace: string    #必填,Pod所屬的命名空間
  labels:      #自定義標簽
    - name: string     #自定義標簽名字<key: value>
  annotations:       #自定義注釋列表
    - name: string
spec:         #必填,部署的詳細定義
  selector: 
    matchLabels:
      name: string #必填,通過此標簽匹配對應pod<key: value>
  replicas: number #必填,副本數量
  template: #必填,應用容器模版定義
    metadata: 
      labels: 
        name: string #必填,遇上面matchLabels的標簽相同
    spec: 
      containers:      #必填,定義容器列表
      - name: string     #必填,容器名稱
        image: string    #必填,容器的鏡像名稱
        imagePullPolicy: [Always | Never | IfNotPresent] #獲取鏡像的策略 Alawys表示下載鏡像 IfnotPresent表示優先使用本地鏡像,否則下載鏡像,Nerver表示僅使用本地鏡像
        command: [string]    #容器的啟動命令列表,如不指定,使用打包時使用的啟動命令
        args: [string]     #容器的啟動命令參數列表
        workingDir: string     #選填,容器的工作目錄
        env:       #容器運行前需設置的環境變量列表
        - name: string     #環境變量名稱
          value: string    #環境變量的值
        ports:       #需要暴露的端口庫號列表
        - name: string     #選填,端口號名稱
          containerPort: int   #容器需要監聽的端口號
          hostPort: int    #選填,容器所在主機需要監聽的端口號,默認與Container相同
          protocol: string     #選填,端口協議,支持TCP和UDP,默認TCP
        resources:       #資源限制和請求的設置
          limits:      #資源限制的設置
            cpu: string    #Cpu的限制,單位為core數,將用於docker run --cpu-shares參數
            memory: string     #內存限制,單位可以為Mib/Gib,將用於docker run --memory參數
          requests:      #資源請求的設置
            cpu: string    #Cpu請求,容器啟動的初始可用數量
            memory: string     #內存清楚,容器啟動的初始可用數量
        volumeMounts:    #掛載到容器內部的存儲卷配置
        - name: string     #引用pod定義的共享存儲卷的名稱,需用volumes[]部分定義的的卷名
          mountPath: string    #存儲卷在容器內mount的絕對路徑,應少於512字符
          readOnly: boolean    #是否為只讀模式
        livenessProbe:     #對Pod內個容器健康檢查的設置,當探測無響應幾次后將自動重啟該容器,檢查方法有exec、httpGet和tcpSocket,對一個容器只需設置其中一種方法即可
          exec:      #對Pod容器內檢查方式設置為exec方式
            command: [string]  #exec方式需要制定的命令或腳本
          httpGet:       #對Pod內個容器健康檢查方法設置為HttpGet,需要制定Path、port
            path: string
            port: number
            host: string
            scheme: string
            HttpHeaders:
            - name: string
              value: string
          tcpSocket:     #對Pod內個容器健康檢查方式設置為tcpSocket方式
            port: number
          initialDelaySeconds: 0  #容器啟動完成后首次探測的時間,單位為秒
          timeoutSeconds: 0   #對容器健康檢查探測等待響應的超時時間,單位秒,默認1秒
          periodSeconds: 0    #對容器監控檢查的定期探測時間設置,單位秒,默認10秒一次
          successThreshold: 0
          failureThreshold: 0
          securityContext:
            privileged:false
        #Pod的重啟策略,Always表示一旦不管以何種方式終止運行,kubelet都將重啟,OnFailure表示只有Pod以非0退出碼退出才重啟,Nerver表示不再重啟該Pod
        restartPolicy: [Always | Never | OnFailure]
        nodeSelector: obeject  #設置NodeSelector表示將該Pod調度到包含這個label的node上,以key:value的格式指定
        imagePullSecrets:    #Pull鏡像時使用的secret名稱,以key:secretkey格式指定
        - name: string
        hostNetwork:false      #是否使用主機網絡模式,默認為false,如果設置為true,表示使用宿主機網絡
        volumes:       #在該pod上定義共享存儲卷列表
        - name: string     #共享存儲卷名稱 (volumes類型有很多種)
          emptyDir: {}     #類型為emtyDir的存儲卷,與Pod同生命周期的一個臨時目錄。為空值
          hostPath: string     #類型為hostPath的存儲卷,表示掛載Pod所在宿主機的目錄
            path: string     #Pod所在宿主機的目錄,將被用於同期中mount的目錄
        - name: string     #共享存儲卷名稱
          secret:      #類型為secret的存儲卷,掛載集群與定義的secre對象到容器內部
            scretname: string  
            items:     
            - key: string     #選擇secrets定義的某個key
              path: string    #文件內容路徑
        - name: string     #共享存儲卷名稱
          configMap:     #類型為configMap的存儲卷,掛載預定義的configMap對象到容器內部
            name: string
            items:
            - key: string     #選擇configmap定義的某個key
              path: string     #文件內容路徑
        - name: string     #共享存儲卷名稱
          persistentVolumeClaim:
            claimName: string     #類型為PVC的持久化存儲卷

更多描述

    /**
     * Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.
     */
    "activeDeadlineSeconds"?: number;
    /**
     * If specified, the pod's scheduling constraints
     */
    "affinity"?: IIoK8sApiCoreV1Affinity;
    /**
     * AutomountServiceAccountToken indicates whether a service account token should be automatically mounted.
     */
    "automountServiceAccountToken"?: boolean;
    /**
     * List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated.
     */
    "containers": Array<IIoK8sApiCoreV1Container>;
    /**
     * Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy.
     */
    "dnsConfig"?: IIoK8sApiCoreV1PodDNSConfig;
    /**
     * Set DNS policy for the pod. Defaults to "ClusterFirst". Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly to 'ClusterFirstWithHostNet'.
     */
    "dnsPolicy"?: string;
    /**
     * EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true.
     */
    "enableServiceLinks"?: boolean;
    /**
     * List of ephemeral containers run in this pod. Ephemeral containers may be run in an existing pod to perform user-initiated actions such as debugging. This list cannot be specified when creating a pod, and it cannot be modified by updating the pod spec. In order to add an ephemeral container to an existing pod, use the pod's ephemeralcontainers subresource. This field is alpha-level and is only honored by servers that enable the EphemeralContainers feature.
     */
    "ephemeralContainers"?: Array<IIoK8sApiCoreV1EphemeralContainer>;
    /**
     * HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts file if specified. This is only valid for non-hostNetwork pods.
     */
    "hostAliases"?: Array<IIoK8sApiCoreV1HostAlias>;
    /**
     * Use the host's ipc namespace. Optional: Default to false.
     */
    "hostIPC"?: boolean;
    /**
     * Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified. Default to false.
     */
    "hostNetwork"?: boolean;
    /**
     * Use the host's pid namespace. Optional: Default to false.
     */
    "hostPID"?: boolean;
    /**
     * Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value.
     */
    "hostname"?: string;
    /**
     * ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod
     */
    "imagePullSecrets"?: Array<IIoK8sApiCoreV1LocalObjectReference>;
    /**
     * List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
     */
    "initContainers"?: Array<IIoK8sApiCoreV1Container>;
    /**
     * 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.
     */
    "nodeName"?: 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"?: {
        [key: string]: string;
    };
    /**
     * Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. This field will be autopopulated at admission time by the RuntimeClass admission controller. If the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. The RuntimeClass admission controller will reject Pod create requests which have the overhead already set. If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value defined in the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. More info: https://git.k8s.io/enhancements/keps/sig-node/20190226-pod-overhead.md This field is alpha-level as of Kubernetes v1.16, and is only honored by servers that enable the PodOverhead feature.
     */
    "overhead"?: {
        [key: string]: IIoK8sApimachineryPkgApiResourceQuantity;
    };
    /**
     * PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. This field is alpha-level and is only honored by servers that enable the NonPreemptingPriority feature.
     */
    "preemptionPolicy"?: string;
    /**
     * The priority value. Various system components use this field to find the priority of the pod. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority.
     */
    "priority"?: number;
    /**
     * If specified, indicates the pod's priority. "system-node-critical" and "system-cluster-critical" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default.
     */
    "priorityClassName"?: string;
    /**
     * If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to "True" 

     */
    "readinessGates"?: Array<IIoK8sApiCoreV1PodReadinessGate>;
    /**
     * Restart policy for all containers within the pod. One of Always, OnFailure, Never. Default to Always. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
     */
    "restartPolicy"?: string;
    /**
     * RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod.  If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the "legacy" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler.
     */
    "runtimeClassName"?: string;
    /**
     * If specified, the pod will be dispatched by specified scheduler. If not specified, the pod will be dispatched by default scheduler.
     */
    "schedulerName"?: string;
    /**
     * SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty.  See type description for default values of each field.
     */
    "securityContext"?: IIoK8sApiCoreV1PodSecurityContext;
    /**
     * DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. Deprecated: Use serviceAccountName instead.
     */
    "serviceAccount"?: string;
    /**
     * ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
     */
    "serviceAccountName"?: string;
    /**
     * Share a single process namespace between all of the containers in a pod. When this is set containers will be able to view and signal processes from other containers in the same pod, and the first process in each container will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both be set. Optional: Default to false.
     */
    "shareProcessNamespace"?: boolean;
    /**
     * If specified, the fully qualified Pod hostname will be "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>". If not specified, the pod will not have a domainname at all.
     */
    "subdomain"?: string;
    /**
     * Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 30 seconds.
     */
    "terminationGracePeriodSeconds"?: number;
    /**
     * If specified, the pod's tolerations.
     */
    "tolerations"?: Array<IIoK8sApiCoreV1Toleration>;
    /**
     * TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. Scheduler will schedule pods in a way which abides by the constraints. This field is only honored by clusters that enable the EvenPodsSpread feature. All topologySpreadConstraints are ANDed.
     */
    "topologySpreadConstraints"?: Array<IIoK8sApiCoreV1TopologySpreadConstraint>;
    /**
     * List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes
     */
    "volumes"?: Array<IIoK8sApiCoreV1Volume>;

參考文檔

https://www.kubernetes.org.cn/1414.html


免責聲明!

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



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