metadata嵌套字段

metadata字段用于描述对象的属性信息,其内嵌多个字段用于定义资源的元素据,例如name和labels等,这些字段大体可以分为必选字段和可选字段两大类。名称空间级别的资源的必选字段包括如下三项

  • namespace: 指定当前对象隶属于的名称空间,默认值为default
  • name: 设置当前对象的名称,在其所属的名称空间的同一类型中必须唯一
  • uid:当前对象的唯一标识符,其唯一性仅发生在特定的时间段和名称空间中,此标识符主要是用于区别拥有同样名字的“已删除”和“重新创建”的同一个名称的对象
    可选字段通常是由K8S系统自行维护和设置,或者存在默认,或者本身允许使用空值等类型的字段,常用的有如下几个
  • labels:用于标识当前对象的标签,键值数据,常用用于挑选条件,常被用于挑选条件
  • annotations:非标识型键值数据,用来作为挑选条件,用于labels的补充
  • resourceVersion:当前对象的内部版本标识符,用于让客户端确定对象是否变动
  • generation:用于标识当前对象目标状态的代别
  • creationTimestamp:当前对象创建日期的时间戳
  • deletionTimestamp:当前对象删除日期的时间戳
    此外,用户通过配置清单创建资源对象时,通常仅需给出必选字段,可选字段可按需指定,对于用户未明确定义的嵌套字段,则需要由一系列的finalizer组件自动填充。而用户需要对资源创建的目标资源对象进行强制校验,或者在修改时需要用到initializer组件完成。例如,为每个待创建的Pod对象添加一个Sidecar容器等。不同的资源类型也会存在一些专用的嵌套字段,例如ConfigMap资源还支持使用clusterName等

spec和status字段

k8s用spec来描述所期望的对象应该具有的状态,而用status字段来记录对象在当前系统上的当前状态,因此status字段仅对活动对象才有意义。这两个字段都属于嵌套类型的字段。在定义资源配置清单时,status字段则记录了当前对象的当前状态(或实际状态),此这段值由K8S系统负责填充或更新,用户不能手动进行定义。master的controller-manager通过相应的控制器组件动态管理并确保对象的实际状态匹配用户所期望的状态,它是一种调和(reconciliation)配置系统 例如,deployment是一种用于描述集群中运行的应用的对象。因此,创建Deployment类型的对象时,需要为目标Deployment对象设定spec,指定期望需要运行的Pod副本数量,使用的标签选择以及Pod模板等。K8S系统读取待创建的Deployment对象的spec以及系统上相应的活动对象的当前状态,必要时进行对象更新以确保status字段吻合spec字段中定义的期望状态。如果这其中任一实例出现问题(status字段值发生了变化),那么K8S系统则需要及时对spec和status字段的差异作出响应,例如,补足缺失的Pod副本数量等 spec字段嵌套的字段对于不同的对象类型来说也各不相同,具体需要参照K8S API参考手册中的说明进行获取,核心字段对象的常用配置字段后面会进行讲解

资源配置清单格式文档

定义资源配置清单时,尽管apiVersion、kind和metadata字段由章可循,但spec字段对不同的资源来说却是千差万别的,因此用户需要参考K8S API的参考文档来了解各种可用属性字段。好在,K8S在系统上内建了相关的文档,用户可以使用kubectl explain命令直接获取相关的使用帮助,它根据给出的对象类型或相应的嵌套字段来显示相关的下一级文档。例如,要了解Pod资源的一级字典,可以使用类似如下的命令,命令结果会输出支持使用的各一级字段及其说明

  1. [root@k8s-master01 nginx]# clear
  2. [root@k8s-master01 nginx]# kubectl explain pod
  3. KIND: Pod
  4. VERSION: v1
  5. DESCRIPTION:
  6. Pod is a collection of containers that can run on a host. This resource is
  7. created by clients and scheduled onto hosts.
  8. FIELDS:
  9. apiVersion <string>
  10. APIVersion defines the versioned schema of this representation of an
  11. object. Servers should convert recognized schemas to the latest internal
  12. value, and may reject unrecognized values. More info:
  13. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
  14. kind <string>
  15. Kind is a string value representing the REST resource this object
  16. represents. Servers may infer this from the endpoint the client submits
  17. requests to. Cannot be updated. In CamelCase. More info:
  18. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
  19. metadata <Object>
  20. Standard object's metadata. More info:
  21. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
  22. spec <Object>
  23. Specification of the desired behavior of the pod. More info:
  24. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
  25. status <Object>
  26. Most recently observed status of the pod. This data may not be up to date.
  27. Populated by the system. Read-only. More info:
  28. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
  29. [root@k8s-master01 nginx]#

需要了解某一级字段标识的对象的二级字段时,则需要指定其一级字段的对象名称即可,三级和四级字段对象等的查看方式也是以此类推,例如查看Pod资源的spec对象支持嵌套和使用的二级字段

  1. [root@k8s-master01 nginx]# kubectl explain pod.spec
  2. KIND: Pod
  3. VERSION: v1
  4. RESOURCE: spec <Object>
  5. DESCRIPTION:
  6. Specification of the desired behavior of the pod. More info:
  7. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
  8. PodSpec is a description of a pod.
  9. FIELDS:
  10. activeDeadlineSeconds <integer>
  11. Optional duration in seconds the pod may be active on the node relative to
  12. StartTime before the system will actively try to mark it failed and kill
  13. associated containers. Value must be a positive integer.
  14. affinity <Object>
  15. If specified, the pod's scheduling constraints
  16. automountServiceAccountToken <boolean>
  17. AutomountServiceAccountToken indicates whether a service account token
  18. should be automatically mounted.
  19. containers <[]Object> -required-
  20. List of containers belonging to the pod. Containers cannot currently be
  21. added or removed. There must be at least one container in a Pod. Cannot be
  22. updated.
  23. dnsConfig <Object>
  24. Specifies the DNS parameters of a pod. Parameters specified here will be
  25. merged to the generated DNS configuration based on DNSPolicy.
  26. dnsPolicy <string>
  27. Set DNS policy for the pod. Defaults to "ClusterFirst". Valid values are
  28. 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS
  29. parameters given in DNSConfig will be merged with the policy selected with
  30. DNSPolicy. To have DNS options set along with hostNetwork, you have to
  31. specify DNS policy explicitly to 'ClusterFirstWithHostNet'.
  32. enableServiceLinks <boolean>
  33. EnableServiceLinks indicates whether information about services should be
  34. injected into pod's environment variables, matching the syntax of Docker
  35. links. Optional: Defaults to true.
  36. ephemeralContainers <[]Object>
  37. List of ephemeral containers run in this pod. Ephemeral containers may be
  38. run in an existing pod to perform user-initiated actions such as debugging.
  39. This list cannot be specified when creating a pod, and it cannot be
  40. modified by updating the pod spec. In order to add an ephemeral container
  41. to an existing pod, use the pod's ephemeralcontainers subresource. This
  42. field is alpha-level and is only honored by servers that enable the
  43. EphemeralContainers feature.
  44. hostAliases <[]Object>
  45. HostAliases is an optional list of hosts and IPs that will be injected into
  46. the pod's hosts file if specified. This is only valid for non-hostNetwork
  47. pods.
  48. hostIPC <boolean>
  49. Use the host's ipc namespace. Optional: Default to false.
  50. hostNetwork <boolean>
  51. Host networking requested for this pod. Use the host's network namespace.
  52. If this option is set, the ports that will be used must be specified.
  53. Default to false.
  54. hostPID <boolean>
  55. Use the host's pid namespace. Optional: Default to false.
  56. hostname <string>
  57. Specifies the hostname of the Pod If not specified, the pod's hostname will
  58. be set to a system-defined value.
  59. imagePullSecrets <[]Object>
  60. ImagePullSecrets is an optional list of references to secrets in the same
  61. namespace to use for pulling any of the images used by this PodSpec. If
  62. specified, these secrets will be passed to individual puller
  63. implementations for them to use. For example, in the case of docker, only
  64. DockerConfig type secrets are honored. More info:
  65. https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod
  66. initContainers <[]Object>
  67. List of initialization containers belonging to the pod. Init containers are
  68. executed in order prior to containers being started. If any init container
  69. fails, the pod is considered to have failed and is handled according to its
  70. restartPolicy. The name for an init container or normal container must be
  71. unique among all containers. Init containers may not have Lifecycle
  72. actions, Readiness probes, Liveness probes, or Startup probes. The
  73. resourceRequirements of an init container are taken into account during
  74. scheduling by finding the highest request/limit for each resource type, and
  75. then using the max of of that value or the sum of the normal containers.
  76. Limits are applied to init containers in a similar fashion. Init containers
  77. cannot currently be added or removed. Cannot be updated. More info:
  78. https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
  79. nodeName <string>
  80. NodeName is a request to schedule this pod onto a specific node. If it is
  81. non-empty, the scheduler simply schedules this pod onto that node, assuming
  82. that it fits resource requirements.
  83. nodeSelector <map[string]string>
  84. NodeSelector is a selector which must be true for the pod to fit on a node.
  85. Selector which must match a node's labels for the pod to be scheduled on
  86. that node. More info:
  87. https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
  88. overhead <map[string]string>
  89. Overhead represents the resource overhead associated with running a pod for
  90. a given RuntimeClass. This field will be autopopulated at admission time by
  91. the RuntimeClass admission controller. If the RuntimeClass admission
  92. controller is enabled, overhead must not be set in Pod create requests. The
  93. RuntimeClass admission controller will reject Pod create requests which
  94. have the overhead already set. If RuntimeClass is configured and selected
  95. in the PodSpec, Overhead will be set to the value defined in the
  96. corresponding RuntimeClass, otherwise it will remain unset and treated as
  97. zero. More info:
  98. https://git.k8s.io/enhancements/keps/sig-node/20190226-pod-overhead.md This
  99. field is alpha-level as of Kubernetes v1.16, and is only honored by servers
  100. that enable the PodOverhead feature.
  101. preemptionPolicy <string>
  102. PreemptionPolicy is the Policy for preempting pods with lower priority. One
  103. of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.
  104. This field is alpha-level and is only honored by servers that enable the
  105. NonPreemptingPriority feature.
  106. priority <integer>
  107. The priority value. Various system components use this field to find the
  108. priority of the pod. When Priority Admission Controller is enabled, it
  109. prevents users from setting this field. The admission controller populates
  110. this field from PriorityClassName. The higher the value, the higher the
  111. priority.
  112. priorityClassName <string>
  113. If specified, indicates the pod's priority. "system-node-critical" and
  114. "system-cluster-critical" are two special keywords which indicate the
  115. highest priorities with the former being the highest priority. Any other
  116. name must be defined by creating a PriorityClass object with that name. If
  117. not specified, the pod priority will be default or zero if there is no
  118. default.
  119. readinessGates <[]Object>
  120. If specified, all readiness gates will be evaluated for pod readiness. A
  121. pod is ready when all its containers are ready AND all conditions specified
  122. in the readiness gates have status equal to "True" More info:
  123. https://git.k8s.io/enhancements/keps/sig-network/0007-pod-ready%2B%2B.md
  124. restartPolicy <string>
  125. Restart policy for all containers within the pod. One of Always, OnFailure,
  126. Never. Default to Always. More info:
  127. https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
  128. runtimeClassName <string>
  129. RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group,
  130. which should be used to run this pod. If no RuntimeClass resource matches
  131. the named class, the pod will not be run. If unset or empty, the "legacy"
  132. RuntimeClass will be used, which is an implicit class with an empty
  133. definition that uses the default runtime handler. More info:
  134. https://git.k8s.io/enhancements/keps/sig-node/runtime-class.md This is a
  135. beta feature as of Kubernetes v1.14.
  136. schedulerName <string>
  137. If specified, the pod will be dispatched by specified scheduler. If not
  138. specified, the pod will be dispatched by default scheduler.
  139. securityContext <Object>
  140. SecurityContext holds pod-level security attributes and common container
  141. settings. Optional: Defaults to empty. See type description for default
  142. values of each field.
  143. serviceAccount <string>
  144. DeprecatedServiceAccount is a depreciated alias for ServiceAccountName.
  145. Deprecated: Use serviceAccountName instead.
  146. serviceAccountName <string>
  147. ServiceAccountName is the name of the ServiceAccount to use to run this
  148. pod. More info:
  149. https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
  150. shareProcessNamespace <boolean>
  151. Share a single process namespace between all of the containers in a pod.
  152. When this is set containers will be able to view and signal processes from
  153. other containers in the same pod, and the first process in each container
  154. will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both
  155. be set. Optional: Default to false. This field is beta-level and may be
  156. disabled with the PodShareProcessNamespace feature.
  157. subdomain <string>
  158. If specified, the fully qualified Pod hostname will be
  159. "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>". If not
  160. specified, the pod will not have a domainname at all.
  161. terminationGracePeriodSeconds <integer>
  162. Optional duration in seconds the pod needs to terminate gracefully. May be
  163. decreased in delete request. Value must be non-negative integer. The value
  164. zero indicates delete immediately. If this value is nil, the default grace
  165. period will be used instead. The grace period is the duration in seconds
  166. after the processes running in the pod are sent a termination signal and
  167. the time when the processes are forcibly halted with a kill signal. Set
  168. this value longer than the expected cleanup time for your process. Defaults
  169. to 30 seconds.
  170. tolerations <[]Object>
  171. If specified, the pod's tolerations.
  172. topologySpreadConstraints <[]Object>
  173. TopologySpreadConstraints describes how a group of pods ought to spread
  174. across topology domains. Scheduler will schedule pods in a way which abides
  175. by the constraints. This field is alpha-level and is only honored by
  176. clusters that enables the EvenPodsSpread feature. All
  177. topologySpreadConstraints are ANDed.
  178. volumes <[]Object>
  179. List of volumes that can be mounted by containers belonging to the pod.
  180. More info: https://kubernetes.io/docs/concepts/storage/volumes
  181. [root@k8s-master01 nginx]#

spec字段的文档通常包含RESOURCE、DESCRIPTION和FIELDS几节,其中FIELDS节中给出了可嵌套使用使用的字段,数据类型及其功能描述。例如,上面命令的结果显示在FIELDS中的containers字段的数据类型是一个对象列表([]onject),而且是一个必选字段。任何值为对象(object)类型字段都会嵌套一到多个下一级字段,例如Pod对象中的每个容器也是对象类型数据,它同样包含嵌套字段,但容器不支持单独创建,而是需要包含于Pod对象的上下文中

  1. [root@k8s-master01 nginx]# kubectl explain pod.spec.containers
  2. KIND: Pod
  3. VERSION: v1
  4. RESOURCE: containers <[]Object>
  5. DESCRIPTION:
  6. List of containers belonging to the pod. Containers cannot currently be
  7. added or removed. There must be at least one container in a Pod. Cannot be
  8. updated.
  9. A single application container that you want to run within a pod.
  10. FIELDS:
  11. args <[]string>
  12. Arguments to the entrypoint. The docker image's CMD is used if this is not
  13. provided. Variable references $(VAR_NAME) are expanded using the
  14. container's environment. If a variable cannot be resolved, the reference in
  15. the input string will be unchanged. The $(VAR_NAME) syntax can be escaped
  16. with a double $$, ie: $$(VAR_NAME). Escaped references will never be
  17. expanded, regardless of whether the variable exists or not. Cannot be
  18. updated. More info:
  19. https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
  20. command <[]string>
  21. Entrypoint array. Not executed within a shell. The docker image's
  22. ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME)
  23. are expanded using the container's environment. If a variable cannot be
  24. resolved, the reference in the input string will be unchanged. The
  25. $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME).
  26. Escaped references will never be expanded, regardless of whether the
  27. variable exists or not. Cannot be updated. More info:
  28. https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
  29. env <[]Object>
  30. List of environment variables to set in the container. Cannot be updated.
  31. envFrom <[]Object>
  32. List of sources to populate environment variables in the container. The
  33. keys defined within a source must be a C_IDENTIFIER. All invalid keys will
  34. be reported as an event when the container is starting. When a key exists
  35. in multiple sources, the value associated with the last source will take
  36. precedence. Values defined by an Env with a duplicate key will take
  37. precedence. Cannot be updated.
  38. image <string>
  39. Docker image name. More info:
  40. https://kubernetes.io/docs/concepts/containers/images This field is
  41. optional to allow higher level config management to default or override
  42. container images in workload controllers like Deployments and StatefulSets.
  43. imagePullPolicy <string>
  44. Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always
  45. if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated.
  46. More info:
  47. https://kubernetes.io/docs/concepts/containers/images#updating-images
  48. lifecycle <Object>
  49. Actions that the management system should take in response to container
  50. lifecycle events. Cannot be updated.
  51. livenessProbe <Object>
  52. Periodic probe of container liveness. Container will be restarted if the
  53. probe fails. Cannot be updated. More info:
  54. https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
  55. name <string> -required-
  56. Name of the container specified as a DNS_LABEL. Each container in a pod
  57. must have a unique name (DNS_LABEL). Cannot be updated.
  58. ports <[]Object>
  59. List of ports to expose from the container. Exposing a port here gives the
  60. system additional information about the network connections a container
  61. uses, but is primarily informational. Not specifying a port here DOES NOT
  62. prevent that port from being exposed. Any port which is listening on the
  63. default "0.0.0.0" address inside a container will be accessible from the
  64. network. Cannot be updated.
  65. readinessProbe <Object>
  66. Periodic probe of container service readiness. Container will be removed
  67. from service endpoints if the probe fails. Cannot be updated. More info:
  68. https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
  69. resources <Object>
  70. Compute Resources required by this container. Cannot be updated. More info:
  71. https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/
  72. securityContext <Object>
  73. Security options the pod should run with. More info:
  74. https://kubernetes.io/docs/concepts/policy/security-context/ More info:
  75. https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
  76. startupProbe <Object>
  77. StartupProbe indicates that the Pod has successfully initialized. If
  78. specified, no other probes are executed until this completes successfully.
  79. If this probe fails, the Pod will be restarted, just as if the
  80. livenessProbe failed. This can be used to provide different probe
  81. parameters at the beginning of a Pod's lifecycle, when it might take a long
  82. time to load data or warm a cache, than during steady-state operation. This
  83. cannot be updated. This is an alpha feature enabled by the StartupProbe
  84. feature flag. More info:
  85. https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
  86. stdin <boolean>
  87. Whether this container should allocate a buffer for stdin in the container
  88. runtime. If this is not set, reads from stdin in the container will always
  89. result in EOF. Default is false.
  90. stdinOnce <boolean>
  91. Whether the container runtime should close the stdin channel after it has
  92. been opened by a single attach. When stdin is true the stdin stream will
  93. remain open across multiple attach sessions. If stdinOnce is set to true,
  94. stdin is opened on container start, is empty until the first client
  95. attaches to stdin, and then remains open and accepts data until the client
  96. disconnects, at which time stdin is closed and remains closed until the
  97. container is restarted. If this flag is false, a container processes that
  98. reads from stdin will never receive an EOF. Default is false
  99. terminationMessagePath <string>
  100. Optional: Path at which the file to which the container's termination
  101. message will be written is mounted into the container's filesystem. Message
  102. written is intended to be brief final status, such as an assertion failure
  103. message. Will be truncated by the node if greater than 4096 bytes. The
  104. total message length across all containers will be limited to 12kb.
  105. Defaults to /dev/termination-log. Cannot be updated.
  106. terminationMessagePolicy <string>
  107. Indicate how the termination message should be populated. File will use the
  108. contents of terminationMessagePath to populate the container status message
  109. on both success and failure. FallbackToLogsOnError will use the last chunk
  110. of container log output if the termination message file is empty and the
  111. container exited with an error. The log output is limited to 2048 bytes or
  112. 80 lines, whichever is smaller. Defaults to File. Cannot be updated.
  113. tty <boolean>
  114. Whether this container should allocate a TTY for itself, also requires
  115. 'stdin' to be true. Default is false.
  116. volumeDevices <[]Object>
  117. volumeDevices is the list of block devices to be used by the container.
  118. This is a beta feature.
  119. volumeMounts <[]Object>
  120. Pod volumes to mount into the container's filesystem. Cannot be updated.
  121. workingDir <string>
  122. Container's working directory. If not specified, the container runtime's
  123. default will be used, which might be configured in the container image.
  124. Cannot be updated.
  125. [root@k8s-master01 nginx]#

内建文档大大降低了用户手动创建资源配置时的难度,尝试使用某个资源类型时候,explain也的确是用户的常用命令之一。熟悉各常用字段的功能之后,以同类型的现有活动对象的清单为模板可以更快的生成目标目标资源的配置文件,命令格式为kubectl get TYPE/NAME -o yaml --export,其中—export选项用于省略输出由系统生成的信息。例如,基于现在的deployment对象名称为my-nginx生成的对象生成一个deploy-demo.yaml文件

  1. [root@k8s-master01 nginx]# kubectl get deployment
  2. NAME READY UP-TO-DATE AVAILABLE AGE
  3. my-nginx 5/5 5 5 6d14h
  4. [root@k8s-master01 nginx]#
  5. [root@k8s-master01 nginx]# kubectl get deployment my-nginx -o yaml --export > deploy-demo.yaml
  6. Flag --export has been deprecated, This flag is deprecated and will be removed in future.
  7. [root@k8s-master01 nginx]#
  8. #这里的报错不用管它,它提示说--export将被弃用移除
  9. [root@k8s-master01 nginx]# cat deploy-demo.yaml
  10. apiVersion: apps/v1
  11. kind: Deployment
  12. metadata:
  13. annotations:
  14. deployment.kubernetes.io/revision: "1"
  15. kubectl.kubernetes.io/last-applied-configuration: |
  16. {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"name":"my-nginx","namespace":"default"},"spec":{"replicas":5,"selector":{"matchLabels":{"app":"my-nginx"}},"template":{"metadata":{"labels":{"app":"my-nginx"}},"spec":{"containers":[{"image":"daocloud.io/library/nginx:1.13.0-alpine","name":"my-nginx","ports":[{"containerPort":80}]}]}}}}
  17. creationTimestamp: null
  18. generation: 1
  19. name: my-nginx
  20. selfLink: /apis/apps/v1/namespaces/default/deployments/my-nginx
  21. spec:
  22. progressDeadlineSeconds: 600
  23. replicas: 5
  24. revisionHistoryLimit: 10
  25. selector:
  26. matchLabels:
  27. app: my-nginx
  28. strategy:
  29. rollingUpdate:
  30. maxSurge: 25%
  31. maxUnavailable: 25%
  32. type: RollingUpdate
  33. template:
  34. metadata:
  35. creationTimestamp: null
  36. labels:
  37. app: my-nginx
  38. spec:
  39. containers:
  40. - image: daocloud.io/library/nginx:1.13.0-alpine
  41. imagePullPolicy: IfNotPresent
  42. name: my-nginx
  43. ports:
  44. - containerPort: 80
  45. protocol: TCP
  46. resources: {}
  47. terminationMessagePath: /dev/termination-log
  48. terminationMessagePolicy: File
  49. dnsPolicy: ClusterFirst
  50. restartPolicy: Always
  51. schedulerName: default-scheduler
  52. securityContext: {}
  53. terminationGracePeriodSeconds: 30
  54. status: {}
  55. [root@k8s-master01 nginx]#
  56. 可以看到已经基于my-nginxdeployment生成了一个yaml格式的配置清单,只需要手动修改为自己需要的期望状态即可运行了

通过资源清单文件管理资源对象比之前通过命令行方式操作有很大的优势,具体包括命令行的操作仅支持部分资源对象的部分属性,而资源清单支持配置资源的所有属性字段,而且使用配置清单文件还能够进行版本追踪,复查等高级功能的操作

资源对象管理方式

K8S的API Server遵循声明式编程范式而设计,侧重于构建程序逻辑而无需用户描述实现其流程,用户只需要设定期望的状态,系统就能自行确定需要执行的操作以确保达到用户期望的状态,例如,期望某Deployment控制器管理三个Pod资源对象时,而系统观察到当前数量却只有两个,于是系统就会知道需要创建一个新的Pod资源来满足用户期望的副本数量。K8S的自愈,自治等功能都依赖于其声明式机制 于此对应的另一种范式称为陈述式编程,代码侧重于通过创建一种告诉计算机如何操作的算法来更改程序状态的语句来完成,它与硬件的工作方式密切相关,通常,代码将使用条件语句,循环和类继承等控制结构。为了便于用户使用,K8S的 API Server也支持陈述式范式,它直接通过命令及其选项完成对像的管理操作,前面用到的run,expose,delete和get等命令都属于此类,执行时用户需要告诉系统要做什么,例如,使用run命令创建一个有着3个Pod对象副本的Deployment对象,或者通过delete命令删除一个名为myapp的Service对象 k8s系统的大部分API对象都有着spec和status两个字段,其中,spec用于让用户定义所期望的状态,系统从中读取相关的定义;而status则是系统观察并写入的当前状态,用户可以从中获取相关的信息。K8S系统通过控制器监控着系统对象,由其负责让系统当前的专状态无限接近用户所期望的状态 kubectl的命令由此可以分为三类:陈述式命苦,陈述式对象配置和声明式对象配置,第一种方式就是此前用到的run、expose、delete、get等命令,他们直接用于K8S系统上的活动对象,简单易用,但不支持代码复用,修改复审及神奇日志等功能,这些功能的使用通常通常需要依赖于资源配置清单。在这种模式下,用户可以访问每个对象的完整模式。 资源清单本质上是一个json或yaml格式的文本文件,由资源对象的配置信息组成,支持使用git等进行版本控制。而用户可以以资源清单为基础,在K8S系统上以陈述式或声明式进行资源对象管理 陈述式管理方式包括create、delete、get和replace等命令,与陈述式命令的不同之处在于,它通过资源配置读取需要管理的目标资源对象。陈述式对象配置的管理操作直接作用于活动对象,即便修改配置清单中的极小一部分内容,使用replace命令进行的对象更新也将会导致整个对象被替换。进一步地,混合使用陈述式命令进行清单文件修改时,必然会导致用户丢失活动对象的当前状态 声明式对象配置并不直接指明要进行的对象管理操作,而是提供配置清单文件给K8S,并委托K8S跟踪活动对象的状态变动。资源对象的创建、删除及修改操作,全都通过唯一的命令apply来完成,并且每次操作时,提供给命令的配置信息都将保存于对象的注解信息中,并通过对比检查活动对象的当前状态、注解中的配置信息及资源清单中的配置信息三方进行变更合并,从而实现仅修改变动字段的高级补丁机制 陈述对象配置相比较于声明式对象配置来说,其缺点在于同一目录下的配置文件必须同时进行同一种操作,例如,要么都创建,要么都更新等。而且其他用户的更新也必须反映在配置文件中,不然其更新在下一次的更新中将会被覆盖。因此,声明式对象配置是优先推荐给用户使用的管理机制 然而,对于新手来说,陈述式命令的配置方式最易于上手,对系统有所了解后易于切换为使用陈述式对象配置管理方式。因此,若推荐给高级用户则推荐使用声明式配置,并建议同时使用版本控制系统存储所期望的状态,以及跨多谢的历史信息,并启用变更复查机制。例外推荐使用借助于kube-applier等一类的项目实现自动化声明式配置,用户将配置推到git仓库中,然后借助此类工具即能将其自动同步到K8S集群之中