創(chuàng)建Kubernetes manifest 指南

更多關(guān)注:https://mknight.cn/

前言

創(chuàng)建編排文件,是一件復(fù)雜的事情,很多時(shí)候可能沒有頭緒該如何開始。所以此篇文章提供一些創(chuàng)建的思路。

在定義資源時(shí),將包含以下字段:

apiVersion: apps/v1
kind: Deployment
metadata:
  ...
spec:
  ... 

以下操作均在1.20.0版本,其他版本命令或結(jié)果有所不同。

字段詳解

apiVersion

該字段指用于創(chuàng)建資源的API組和藥使用的API版本。Kubernetes API被聚合到API組中,v1是要使用的apps API版本。如果想列出可用的API組及其版本,可以使用以下命令:

~ kubectl api-versions 
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
crd.projectcalico.org/v1
discovery.k8s.io/v1beta1
events.k8s.io/v1
events.k8s.io/v1beta1
extensions/v1beta1
flowcontrol.apiserver.k8s.io/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

kind

指定要?jiǎng)?chuàng)建的資源類型,比如Deployment、Pod和ReplicaSet等,可以使用以下命令查看可用的資源類型以及關(guān)聯(lián)的API組:

~ kubectl api-resources | more
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap
endpoints                         ep           v1                                     true         Endpoints
events                            ev           v1                                     true         Event
limitranges                       limits       v1                                     true         LimitRange
namespaces                        ns           v1                                     false        Namespace
nodes                             no           v1                                     false        Node
persistentvolumeclaims            pvc          v1                                     true         PersistentVolum
eClaim
persistentvolumes                 pv           v1                                     false        PersistentVolum
e
pods                              po           v1                                     true         Pod
podtemplates                                   v1                                     true         PodTemplate
replicationcontrollers            rc           v1                                     true         ReplicationCont
roller
resourcequotas                    quota        v1                                     true         ResourceQuota
secrets                                        v1                                     true         Secret
serviceaccounts                   sa           v1                                     true         ServiceAccount
services                          svc          v1                                     true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io/v1        false        MutatingWebhook
Configuration
validatingwebhookconfigurations                admissionregistration.k8s.io/v1        false        ValidatingWebho
okConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1                false        CustomResourceD
efinition
apiservices                                    apiregistration.k8s.io/v1              false        APIService
controllerrevisions                            apps/v1                                true         ControllerRevis
ion
daemonsets                        ds           apps/v1                                true         DaemonSet
deployments                       deploy       apps/v1                                true         Deployment
replicasets                       rs           apps/v1                                true         ReplicaSet
statefulsets                      sts          apps/v1                                true         StatefulSet
tokenreviews                                   authentication.k8s.io/v1               false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io/v1                true         LocalSubjectAcc
essReview
selfsubjectaccessreviews                       authorization.k8s.io/v1                false        SelfSubjectAcce
ssReview
selfsubjectrulesreviews                        authorization.k8s.io/v1                false        SelfSubjectRule
sReview
subjectaccessreviews                           authorization.k8s.io/v1                false        SubjectAccessRe
view
horizontalpodautoscalers          hpa          autoscaling/v1                         true         HorizontalPodAu
toscaler
cronjobs                          cj           batch/v1beta1                          true         CronJob
jobs                                           batch/v1                               true         Job
certificatesigningrequests        csr          certificates.k8s.io/v1                 false        CertificateSign
ingRequest
leases                                         coordination.k8s.io/v1                 true         Lease
bgpconfigurations                              crd.projectcalico.org/v1               false        BGPConfiguratio
n
bgppeers                                       crd.projectcalico.org/v1               false        BGPPeer
blockaffinities                                crd.projectcalico.org/v1               false        BlockAffinity
caliconodestatuses                             crd.projectcalico.org/v1               false        CalicoNodeStatu
s
clusterinformations                            crd.projectcalico.org/v1               false        ClusterInformat
ion
felixconfigurations                            crd.projectcalico.org/v1               false        FelixConfigurat
ion
globalnetworkpolicies                          crd.projectcalico.org/v1               false        GlobalNetworkPo
licy
globalnetworksets                              crd.projectcalico.org/v1               false        GlobalNetworkSe
t
hostendpoints                                  crd.projectcalico.org/v1               false        HostEndpoint
ipamblocks                                     crd.projectcalico.org/v1               false        IPAMBlock
ipamconfigs                                    crd.projectcalico.org/v1               false        IPAMConfig
ipamhandles                                    crd.projectcalico.org/v1               false        IPAMHandle
ippools                                        crd.projectcalico.org/v1               false        IPPool
ipreservations                                 crd.projectcalico.org/v1               false        IPReservation
kubecontrollersconfigurations                  crd.projectcalico.org/v1               false        KubeControllers
Configuration
networkpolicies                                crd.projectcalico.org/v1               true         NetworkPolicy
networksets                                    crd.projectcalico.org/v1               true         NetworkSet
endpointslices                                 discovery.k8s.io/v1beta1               true         EndpointSlice
events                            ev           events.k8s.io/v1                       true         Event
ingresses                         ing          extensions/v1beta1                     true         Ingress
flowschemas                                    flowcontrol.apiserver.k8s.io/v1beta1   false        FlowSchema
prioritylevelconfigurations                    flowcontrol.apiserver.k8s.io/v1beta1   false        PriorityLevelCo
nfiguration
ingressclasses                                 networking.k8s.io/v1                   false        IngressClass
ingresses                         ing          networking.k8s.io/v1                   true         Ingress
networkpolicies                   netpol       networking.k8s.io/v1                   true         NetworkPolicy
runtimeclasses                                 node.k8s.io/v1                         false        RuntimeClass
poddisruptionbudgets              pdb          policy/v1beta1                         true         PodDisruptionBu
dget
podsecuritypolicies               psp          policy/v1beta1                         false        PodSecurityPoli
cy
clusterrolebindings                            rbac.authorization.k8s.io/v1           false        ClusterRoleBind
ing
clusterroles                                   rbac.authorization.k8s.io/v1           false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io/v1           true         RoleBinding
roles                                          rbac.authorization.k8s.io/v1           true         Role
priorityclasses                   pc           scheduling.k8s.io/v1                   false        PriorityClass
csidrivers                                     storage.k8s.io/v1                      false        CSIDriver
csinodes                                       storage.k8s.io/v1                      false        CSINode
storageclasses                    sc           storage.k8s.io/v1                      false        StorageClass
volumeattachments                              storage.k8s.io/v1                      false        VolumeAttachmen
t

使用api-versionapi-resources命令可以找到可用資源與資源類型關(guān)聯(lián)的API組以及API組版本。根據(jù)此信息填寫apiVersion:kind:字段。

如果想了解某種資源類型的用途,可以使用kubectl explain命令:

~ kubectl explain --api-version=apps/v1 deployment
KIND:     Deployment
VERSION:  apps/v1

DESCRIPTION:
     Deployment enables declarative updates for Pods and ReplicaSets.

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/sig-architecture/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/sig-architecture/api-conventions.md#types-kinds

   metadata <Object>
     Standard object metadata.

   spec <Object>
     Specification of the desired behavior of the Deployment.

   status   <Object>
     Most recently observed status of the Deployment.

metadata

用于唯一標(biāo)識(shí)Kubernetes集群中的資源,可以為資源命名、分配標(biāo)簽、注解和指定命名空間等。

$ kubectl explain deployment.metadata | more
KIND:     Deployment
VERSION:  apps/v1

RESOURCE: metadata <Object>

DESCRIPTION:
     Standard object metadata.
                                                                                                                                             
     ObjectMeta is metadata that all persisted resources must have, which
     includes all objects users must create.

FIELDS:
   annotations  <map[string]string>
     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
...

spec

可以定義要使用的容器鏡像、副本數(shù)量、selector條件、存活或就緒探針的定義等。查看具體信息可以使用以下命令:

~ kubectl explain deployment.spec | more
KIND:     Deployment
VERSION:  apps/v1

RESOURCE: spec <Object>

DESCRIPTION:
     Specification of the desired behavior of the Deployment.

     DeploymentSpec is the specification of the desired behavior of the
     Deployment.

FIELDS:
   minReadySeconds  <integer>
     Minimum number of seconds for which a newly created pod should be ready
     without any of its container crashing, for it to be considered available.
     Defaults to 0 (pod will be considered available as soon as it is ready)

   paused   <boolean>
     Indicates that the deployment is paused.

   progressDeadlineSeconds  <integer>
     The maximum time in seconds for a deployment to make progress before it is
     considered to be failed. The deployment controller will continue to process
     failed deployments and a condition with a ProgressDeadlineExceeded reason
     will be surfaced in the deployment status. Note that progress will not be
     estimated during the time a deployment is paused. Defaults to 600s.

   replicas <integer>
     Number of desired pods. This is a pointer to distinguish between explicit
     zero and not specified. Defaults to 1.

   revisionHistoryLimit <integer>
     The number of old ReplicaSets to retain to allow rollback. This is a
     pointer to distinguish between explicit zero and not specified. Defaults to
     10.

   selector <Object> -required-
     Label selector for pods. Existing ReplicaSets whose pods are selected by
     this will be the ones affected by this deployment. It must match the pod
     template's labels.

   strategy <Object>
     The deployment strategy to use to replace existin

獲取模板

~ kubectl create deployment nginx --image=nginx -o yaml --dry-run=client
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: nginx
  name: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
status: {}

或者ingress

~ kubectl create ingress my-ingress --rule=host/path=app1:80 -o yaml --dry-run=client
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  creationTimestamp: null
  name: my-ingress
spec:
  rules:
  - host: host
    http:
      paths:
      - backend:
          service:
            name: app1
            port:
              number: 80
        path: /path
        pathType: Exact
status:
  loadBalancer: {}

還可以使用 kubectl explain 添加--rescursive參數(shù),可以獲取各個(gè)字段的分層視圖:

~ kubectl explain deployment.spec.template.spec.containers.livenessProbe --recursive | more
KIND:     Deployment
VERSION:  apps/v1

RESOURCE: livenessProbe <Object>

DESCRIPTION:
     Periodic probe of container liveness. Container will be restarted if the
     probe fails. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

     Probe describes a health check to be performed against a container to
     determine whether it is alive or ready to receive traffic.

FIELDS:
   exec <Object>
      command   <[]string>
   failureThreshold <integer>
   httpGet  <Object>
      host  <string>
      httpHeaders   <[]Object>
         name   <string>
         value  <string>
      path  <string>
      port  <string>
      scheme    <string>
   initialDelaySeconds  <integer>
   periodSeconds    <integer>
   successThreshold <integer>
   tcpSocket    <Object>
      host  <string>
      port  <string>
   timeoutSeconds   <integer>

如果想進(jìn)一步了解更詳細(xì)的信息,可以繼續(xù)拼接:

[root@k8s-node-217 ~]# kubectl explain deployment.spec.template.spec.containers.lifecycle
KIND:     Deployment
VERSION:  apps/v1

RESOURCE: lifecycle <Object>

DESCRIPTION:
     Actions that the management system should take in response to container
     lifecycle events. Cannot be updated.

     Lifecycle describes actions that the management system should take in
     response to container lifecycle events. For the PostStart and PreStop
     lifecycle handlers, management of the container blocks until the action is
     complete, unless the container process fails, in which case the handler is
     aborted.

FIELDS:
   postStart    <Object>
     PostStart is called immediately after a container is created. If the
     handler fails, the container is terminated and restarted according to its
     restart policy. Other management of the container blocks until the hook
     completes. More info:
     https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks

   preStop  <Object>
     PreStop is called immediately before a container is terminated due to an
     API request or management event such as liveness/startup probe failure,
     preemption, resource contention, etc. The handler is not called if the
     container crashes or exits. The reason for termination is passed to the
     handler. The Pod's termination grace period countdown begins before the
     PreStop hooked is executed. Regardless of the outcome of the handler, the
     container will eventually terminate within the Pod's termination grace
     period. Other management of the container blocks until the hook completes
     or until the termination grace period is reached. More info:
     https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks

總結(jié)

組成

整個(gè)編排文件分為四個(gè)字段或者四部分:

  1. apiVersion API組及版本
  2. kind 資源類型
  3. metadata 資源注解
  4. spec 定義和管理資源

常用命令

# 獲取API 版本
kubectl api-versions
# 獲取資源類型和API版本
kubectl api-resources
# 獲取資源詳情
kubectl explain --api-version=apps/v1 replicaset
# 根據(jù)資源創(chuàng)建基礎(chǔ)模板
kubectl create deployment nginx --image=nginx -o yaml --dry-run=client
# 獲取資源詳情
kubectl explain deployment.spec.selector.matchExpressions.operator
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Kubenetes是當(dāng)前容器編排的事實(shí)標(biāo)準(zhǔn),每個(gè)基于容器開發(fā)應(yīng)用的工程師/架構(gòu)師都應(yīng)該了解Kubenetes的基本...
    DeepNoMind閱讀 791評(píng)論 0 0
  • 大家好,我叫謝偉,是一名程序員。 今天的主題:kubernetes 概念篇,通過一些示例,學(xué)習(xí) kubernete...
    謝小路閱讀 967評(píng)論 1 1
  • 在K8S章節(jié)剛開始我們就介紹了里面的核心組件與架構(gòu)圖,但對(duì)于它們只是有一個(gè)很淺的認(rèn)知,只知道它是干嘛的,對(duì)于它們都...
    Suny____閱讀 754評(píng)論 0 1
  • 1.獲取資源 kubectlget 2.查看資源詳情 kubectl describe <reousrce_typ...
    365a3735241a閱讀 1,068評(píng)論 0 0
  • 三、Kubernetes API Kubernetes 控制面[https://kubernetes.io/zh/...
    Noperx閱讀 281評(píng)論 0 0

友情鏈接更多精彩內(nèi)容