什么是清单

说白了清单是k8s当中用来定义pod的文件,语法格式遵循yaml语法,在yaml当中可以定义控制器类型,元数据,容器端口号等等等....,也可以针对于清单对pod进行删除等操作

为什么学习k8s清单

对于用kubectl命令的方式运行一个或者多个pod会有一定的局限性,比如我们想建立一个自主式pod,不需要任何控制器管理,又或者想定义元数据,一个pod跑多个docker容器,这些操作对于kubectl来说非常麻烦,因此我们应该学会用清单的方式定义pod

pod类型

pod可以分为2种类型:

  • 自助式pod:没有任何控制器的管控
  • 控制器pod:被控制器管控的pod

我们可以用kubectl get命令输出一个pod的配置清单,自主式pod清单定义格式如下

  1. [root@master ~]# kubectl get pods myapp-7c468db58f-qbqhk -o yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. creationTimestamp: "2019-12-08T04:40:44Z"
  6. generateName: myapp-7c468db58f-
  7. labels:
  8. pod-template-hash: 7c468db58f
  9. run: myapp
  10. name: myapp-7c468db58f-qbqhk
  11. namespace: default
  12. ownerReferences:
  13. - apiVersion: apps/v1
  14. blockOwnerDeletion: true
  15. controller: true
  16. kind: ReplicaSet
  17. name: myapp-7c468db58f
  18. uid: a1d7c81d-eb84-4a67-8eab-a423dc260b9f
  19. resourceVersion: ""
  20. selfLink: /api/v1/namespaces/default/pods/myapp-7c468db58f-qbqhk
  21. uid: 68fbd5a8-ee86--837b-730d582884b6
  22. spec:
  23. containers:
  24. - image: ikubernetes/myapp:v1
  25. imagePullPolicy: IfNotPresent
  26. name: myapp
  27. resources: {}
  28. terminationMessagePath: /dev/termination-log
  29. terminationMessagePolicy: File
  30. volumeMounts:
  31. - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
  32. name: default-token-lxfzn
  33. readOnly: true
  34. dnsPolicy: ClusterFirst
  35. enableServiceLinks: true
  36. nodeName: node1
  37. priority:
  38. restartPolicy: Always
  39. schedulerName: default-scheduler
  40. securityContext: {}
  41. serviceAccount: default
  42. serviceAccountName: default
  43. terminationGracePeriodSeconds:
  44. tolerations:
  45. - effect: NoExecute
  46. key: node.kubernetes.io/not-ready
  47. operator: Exists
  48. tolerationSeconds:
  49. - effect: NoExecute
  50. key: node.kubernetes.io/unreachable
  51. operator: Exists
  52. tolerationSeconds:
  53. volumes:
  54. - name: default-token-lxfzn
  55. secret:
  56. defaultMode:
  57. secretName: default-token-lxfzn
  58. status:
  59. conditions:
  60. - lastProbeTime: null
  61. lastTransitionTime: "2019-12-08T04:40:44Z"
  62. status: "True"
  63. type: Initialized
  64. - lastProbeTime: null
  65. lastTransitionTime: "2019-12-08T04:40:46Z"
  66. status: "True"
  67. type: Ready
  68. - lastProbeTime: null
  69. lastTransitionTime: "2019-12-08T04:40:46Z"
  70. status: "True"
  71. type: ContainersReady
  72. - lastProbeTime: null
  73. lastTransitionTime: "2019-12-08T04:40:44Z"
  74. status: "True"
  75. type: PodScheduled
  76. containerStatuses:
  77. - containerID: docker://4d5ddbff59f6baf604746728b65ba60e5826fbf602d0ad9aaafd594bda519bb8
  78. image: ikubernetes/myapp:v1
  79. imageID: docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513
  80. lastState: {}
  81. name: myapp
  82. ready: true
  83. restartCount:
  84. started: true
  85. state:
  86. running:
  87. startedAt: "2019-12-08T04:40:45Z"
  88. hostIP: 192.168.254.11
  89. phase: Running
  90. podIP: 10.244.1.35
  91. podIPs:
  92. - ip: 10.244.1.35
  93. qosClass: BestEffort
  94. startTime: "2019-12-08T04:40:44Z"

可以看到1级字段当中有apiVersion,kind,metadata,spec,status

apiVersion字段

用来指定api的版本,定义的语法格式为group/version,比如我们要定义deployment控制器,那么我们的apiVersion:apps/v1,如果我们要定义自主式pod,那么需要定义apiVersion:v1,这里要注意的是k8s在不断的迭代更新中,有可能新版本中会更换,如果要获取有哪些apiVersion可以用如下命令

  1. [root@master ~]# kubectl api-versions
  2. admissionregistration.k8s.io/v1
  3. admissionregistration.k8s.io/v1beta1
  4. apiextensions.k8s.io/v1
  5. apiextensions.k8s.io/v1beta1
  6. apiregistration.k8s.io/v1
  7. apiregistration.k8s.io/v1beta1
  8. apps/v1
  9. authentication.k8s.io/v1
  10. authentication.k8s.io/v1beta1
  11. authorization.k8s.io/v1
  12. authorization.k8s.io/v1beta1
  13. autoscaling/v1
  14. autoscaling/v2beta1
  15. autoscaling/v2beta2
  16. batch/v1
  17. batch/v1beta1
  18. certificates.k8s.io/v1beta1
  19. coordination.k8s.io/v1
  20. coordination.k8s.io/v1beta1
  21. events.k8s.io/v1beta1
  22. extensions/v1beta1
  23. networking.k8s.io/v1
  24. networking.k8s.io/v1beta1
  25. node.k8s.io/v1beta1
  26. policy/v1beta1
  27. rbac.authorization.k8s.io/v1
  28. rbac.authorization.k8s.io/v1beta1
  29. scheduling.k8s.io/v1
  30. scheduling.k8s.io/v1beta1
  31. storage.k8s.io/v1
  32. storage.k8s.io/v1beta1
  33. v1

kind字段

kind字段主要用于绑定控制器类型,比如:我们想定义一个自助式pod,那么我们就应该定义kind:Pod,如果我们要定义一个deployment控制器管理的pod,那么我们就应该定义kind:Deployment

metadata字段

对于metadata字段为元数据,我们已经知道k8s是通过标签选择器的方式管理pod,因此,在metadata当中最重要的就是标签,我们可以在metadata当中定义名称空间,标签等,我们如果想查看metadata下可以定义哪些元数据可以使用kubectl explain pod.metadata命令来查看,如果想查看metadata子命令下的用法可以继续以点.的方式进行查看,比如:

  1. [root@master ~]# kubectl explain pod.metadata
  2. KIND: Pod
  3. VERSION: v1
  4.  
  5. RESOURCE: metadata <Object>
  6.  
  7. DESCRIPTION:
  8. Standard object's metadata. More info:
  9. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
  10.  
  11. ObjectMeta is metadata that all persisted resources must have, which
  12. includes all objects users must create.
  13.  
  14. FIELDS:
  15. annotations <map[string]string>
  16. Annotations is an unstructured key value map stored with a resource that
  17. may be set by external tools to store and retrieve arbitrary metadata. They
  18. are not queryable and should be preserved when modifying objects. More
  19. info: http://kubernetes.io/docs/user-guide/annotations
  20.  
  21. clusterName <string>
  22. The name of the cluster which the object belongs to. This is used to
  23. distinguish resources with same name and namespace in different clusters.
  24. This field is not set anywhere right now and apiserver is going to ignore
  25. it if set in create or update request.
  26.  
  27. creationTimestamp <string>
  28. CreationTimestamp is a timestamp representing the server time when this
  29. object was created. It is not guaranteed to be set in happens-before order
  30. across separate operations. Clients may not set this value. It is
  31. represented in RFC3339 form and is in UTC. Populated by the system.
  32. Read-only. Null for lists. More info:
  33. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
  34.  
  35. deletionGracePeriodSeconds <integer>
  36. Number of seconds allowed for this object to gracefully terminate before it
  37. will be removed from the system. Only set when deletionTimestamp is also
  38. set. May only be shortened. Read-only.
  39.  
  40. deletionTimestamp <string>
  41. DeletionTimestamp is RFC date and time at which this resource will be
  42. deleted. This field is set by the server when a graceful deletion is
  43. requested by the user, and is not directly settable by a client. The
  44. resource is expected to be deleted (no longer visible from resource lists,
  45. and not reachable by name) after the time in this field, once the
  46. finalizers list is empty. As long as the finalizers list contains items,
  47. deletion is blocked. Once the deletionTimestamp is set, this value may not
  48. be unset or be set further into the future, although it may be shortened or
  49. the resource may be deleted prior to this time. For example, a user may
  50. request that a pod is deleted in seconds. The Kubelet will react by
  51. sending a graceful termination signal to the containers in the pod. After
  52. that seconds, the Kubelet will send a hard termination signal (SIGKILL)
  53. to the container and after cleanup, remove the pod from the API. In the
  54. presence of network partitions, this object may still exist after this
  55. timestamp, until an administrator or automated process can determine the
  56. resource is fully terminated. If not set, graceful deletion of the object
  57. has not been requested. Populated by the system when a graceful deletion is
  58. requested. Read-only. More info:
  59. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
  60.  
  61. finalizers <[]string>
  62. Must be empty before the object is deleted from the registry. Each entry is
  63. an identifier for the responsible component that will remove the entry from
  64. the list. If the deletionTimestamp of the object is non-nil, entries in
  65. this list can only be removed.
  66.  
  67. generateName <string>
  68. GenerateName is an optional prefix, used by the server, to generate a
  69. unique name ONLY IF the Name field has not been provided. If this field is
  70. used, the name returned to the client will be different than the name
  71. passed. This value will also be combined with a unique suffix. The provided
  72. value has the same validation rules as the Name field, and may be truncated
  73. by the length of the suffix required to make the value unique on the
  74. server. If this field is specified and the generated name exists, the
  75. server will NOT return a - instead, it will either return Created
  76. or with Reason ServerTimeout indicating a unique name could not be
  77. found in the time allotted, and the client should retry (optionally after
  78. the time indicated in the Retry-After header). Applied only if Name is not
  79. specified. More info:
  80. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency
  81.  
  82. generation <integer>
  83. A sequence number representing a specific generation of the desired state.
  84. Populated by the system. Read-only.
  85.  
  86. labels <map[string]string>
  87. Map of string keys and values that can be used to organize and categorize
  88. (scope and select) objects. May match selectors of replication controllers
  89. and services. More info: http://kubernetes.io/docs/user-guide/labels
  90.  
  91. managedFields <[]Object>
  92. ManagedFields maps workflow-id and version to the set of fields that are
  93. managed by that workflow. This is mostly for internal housekeeping, and
  94. users typically shouldn't need to set or understand this field. A workflow
  95. can be the user's name, a controller's name, or the name of a specific
  96. apply path like "ci-cd". The set of fields is always in the version that
  97. the workflow used when modifying the object.
  98.  
  99. name <string>
  100. Name must be unique within a namespace. Is required when creating
  101. resources, although some resources may allow a client to request the
  102. generation of an appropriate name automatically. Name is primarily intended
  103. for creation idempotence and configuration definition. Cannot be updated.
  104. More info: http://kubernetes.io/docs/user-guide/identifiers#names
  105.  
  106. namespace <string>
  107. Namespace defines the space within each name must be unique. An empty
  108. namespace is equivalent to the "default" namespace, but "default" is the
  109. canonical representation. Not all objects are required to be scoped to a
  110. namespace - the value of this field for those objects will be empty. Must
  111. be a DNS_LABEL. Cannot be updated. More info:
  112. http://kubernetes.io/docs/user-guide/namespaces
  113.  
  114. ownerReferences <[]Object>
  115. List of objects depended by this object. If ALL objects in the list have
  116. been deleted, this object will be garbage collected. If this object is
  117. managed by a controller, then an entry in this list will point to this
  118. controller, with the controller field set to true. There cannot be more
  119. than one managing controller.
  120.  
  121. resourceVersion <string>
  122. An opaque value that represents the internal version of this object that
  123. can be used by clients to determine when objects have changed. May be used
  124. for optimistic concurrency, change detection, and the watch operation on a
  125. resource or set of resources. Clients must treat these values as opaque and
  126. passed unmodified back to the server. They may only be valid for a
  127. particular resource or set of resources. Populated by the system.
  128. Read-only. Value must be treated as opaque by clients and . More info:
  129. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
  130.  
  131. selfLink <string>
  132. SelfLink is a URL representing this object. Populated by the system.
  133. Read-only. DEPRECATED Kubernetes will stop propagating this field in 1.20
  134. release and the field is planned to be removed in 1.21 release.
  135.  
  136. uid <string>
  137. UID is the unique in time and space value for this object. It is typically
  138. generated by the server on successful creation of a resource and is not
  139. allowed to change on PUT operations. Populated by the system. Read-only.
  140. More info: http://kubernetes.io/docs/user-guide/identifiers#uids

labels:标签选择器,labels的值决定service控制器关联pod的重要选项

namespace:名称空间,默认为default名称空间

name:这里是自主式pod名称,如果是控制器pod,这里是控制器名称

annotations:资源注解,这里跟labels很像,都是键值对,但是不同点是,不能用于挑选资源对象,仅用于“元数据”,在特定场景下注解是“必不可少的”,这一点要注意

spec字段

spec字段是非常重要的字段,用来定义期望容器达到的状态,在spec字段当中可以定义多个容器,容器的名称,容器的镜像,拖取容器镜像的方式,暴露的端口号,存储卷,容器个数等。也就是说真正定义pod是在spec字段当中定义的,spec字段当中有哪些字段可以定义如下:

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

status字段

status字段是反映着当前pod的状态,而status当中的数据会无限接近于spec定义所期望的状态,从而满足用户需要,一般而言,status由k8s自行管理,无需人为操作

定义一个简单的自主式pod如下:

  1. [root@master ~]# cat demo-pod.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. labels:
  6. app: os
  7. namespace: default
  8. name: busybox
  9. spec:
  10. nodeName: node2
  11. containers:
  12. - name: myos
  13. image: busybox
  14. imagePullPolicy: Always
  15. command:
  16. - "/bin/sh"
  17. - "-c"
  18. - "sleep 3600"
  19. ports:
  20. - containerPort:
  21. - name: myweb
  22. image: nginx
  23. imagePullPolicy: Always
  24. ports:
  25. - containerPort:

针对此yaml文件运行pod如下:

  1. [root@master ~]# kubectl create -f demo-pod.yaml
  2. pod/busybox created
  3. [root@master ~]# kubectl get pods --show-labels
  4. NAME READY STATUS RESTARTS AGE LABELS
  5. busybox / Running 24s app=os

针对于一个pod两个容器,如何进入到容器的交互界面呢?-c指定容器名称,如下:

  1. [root@master ~]# kubectl exec -it busybox -c myweb -- /bin/sh
  2. # exit
  3. [root@master ~]# kubectl exec -it busybox -c myos -- /bin/sh
  4. / # ifconfig -a
  5. eth0 Link encap:Ethernet HWaddr ::D6:CD:0B:
  6. inet addr:10.244.2.32 Bcast:0.0.0.0 Mask:255.255.255.0
  7. UP BROADCAST RUNNING MULTICAST MTU: Metric:
  8. RX packets: errors: dropped: overruns: frame:
  9. TX packets: errors: dropped: overruns: carrier:
  10. collisions: txqueuelen:
  11. RX bytes: (690.0 B) TX bytes: (42.0 B)
  12.  
  13. lo Link encap:Local Loopback
  14. inet addr:127.0.0.1 Mask:255.0.0.0
  15. UP LOOPBACK RUNNING MTU: Metric:
  16. RX packets: errors: dropped: overruns: frame:
  17. TX packets: errors: dropped: overruns: carrier:
  18. collisions: txqueuelen:
  19. RX bytes: (0.0 B) TX bytes: (0.0 B)

删除pod

  1. [root@master ~]# kubectl delete pod busybox
  2. pod "busybox" deleted
  3.  
  4. 或者
  5.  
  6. [root@master ~]# kubectl delete -f demo-pod.yaml
  7. pod "busybox" deleted

探针

为什么要有探针,因为探针可以探测pod当中的容器是否正常运行,我们知道容器启动,业务程序未必正常,因此,我们可以用livenessProbe探针来探测业务是否正常,而对于我们新建的pod如果不做就绪性探测,会被前端的service立刻关联,这样有可能导致部分客户端无法正常访问,所欲对于k8s探针主要分为两种,

  • 一种为存活性探测(livenessProbe)
  • 一种为就绪性探测(readinessProbe)

两者探测手段有三种:

  • ExecAction
  • TCPSocketAction
  • HttpGetAction

livenessProbe

例1:ExecAction

  1. [root@master ~]# cat livenessprobe-exec.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: livenessprobe-pod
  6. namespace: default
  7. labels:
  8. app: liveness
  9. spec:
  10. containers:
  11. - name: livenessprobe-container
  12. image: busybox
  13. imagePullPolicy: IfNotPresent
  14. command: ["/bin/sh","-c","touch /tmp/test.txt;sleep 20; rm -rf /tmp/test.txt;sleep 3600"]
  15. livenessProbe:
  16. exec:
  17. command: ["test","-e","/tmp/test.txt"]
  18. initialDelaySeconds:
  19. periodSeconds:
  20. failureThreshold:
  21.  
  22. 验证:可以看到由于文件被删除已经crash了,并且重启了6
  23. [root@master ~]# kubectl get pods
  24. NAME READY STATUS RESTARTS AGE
  25. livenessprobe-pod / CrashLoopBackOff 6 10m

例2:HttpGetAction

  1. [root@master ~]# cat livenessprobe-gethttp.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: livenessprobe-gethttp-pod
  6. namespace: default
  7. labels:
  8. app: liveness-gethttp
  9. spec:
  10. containers:
  11. - name: livenessprobe-gethttp-container
  12. image: nginx
  13. imagePullPolicy: IfNotPresent
  14. livenessProbe:
  15. initialDelaySeconds:
  16. periodSeconds:
  17. failureThreshold:
  18. httpGet:
  19. port:
  20. path: /index.html
  21. 容器跑起来之后删除/usr/share/nginx/html/index.html文件,然后稍等片刻
  22.  
  23. 验证:可以看到容器被重启了一次然后就一直正常运行
  24. [root@master ~]# kubectl get pods
  25. NAME READY STATUS RESTARTS AGE
  26. livenessprobe-gethttp-pod / Running 14m

readinessProbe

  1. [root@master ~]# cat readinessprobe-gethttp.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: livenessprobe-gethttp-pod
  6. namespace: default
  7. labels:
  8. app: liveness-gethttp
  9. spec:
  10. containers:
  11. - name: livenessprobe-gethttp-container
  12. image: nginx
  13. imagePullPolicy: IfNotPresent
  14. readinessProbe:
  15. initialDelaySeconds:
  16. periodSeconds:
  17. failureThreshold:
  18. httpGet:
  19. port:
  20. path: /index.html
  21.  
  22. 验证:
    1.连入容器删除index.html文件
  23. [root@master ~]# kubectl exec -it livenessprobe-gethttp-pod -- /bin/bash
  24. root@livenessprobe-gethttp-pod:/# cd /usr/share/nginx/html/
  25. root@livenessprobe-gethttp-pod:/usr/share/nginx/html# ls
  26. 50x.html index.html
  27. root@livenessprobe-gethttp-pod:/usr/share/nginx/html# rm -rf index.html
  28. root@livenessprobe-gethttp-pod:/usr/share/nginx/html# exit
    2.查看pod状态
  29. [root@master ~]# kubectl get pods -o wide -w
  30. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  31. livenessprobe-gethttp-pod / Running 6s 10.244.1.38 node1 <none> <none>
  32. livenessprobe-gethttp-pod / Running 24s 10.244.1.38 node1 <none> <none>
  33. 3.随后我们在在容器里创建出index.html文件,然后在观察pod
  34. [root@master ~]# kubectl get pods -o wide -w
  35. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  36. livenessprobe-gethttp-pod / Running 6s 10.244.1.38 node1 <none> <none>
  37. livenessprobe-gethttp-pod / Running 24s 10.244.1.38 node1 <none> <none>
  38. livenessprobe-gethttp-pod / Running 2m48s 10.244.1.38 node1 <none> <none>

k8s资产清单(二)的更多相关文章

  1. gitlab-ci + k8s 之k8s (二)

    k8s用自己话说,就是一种容器编排工具,部署好应用,再创建绑定应用的服务,就可以实现的服务访问了.这个理论还是得去看重点谈理论的文章,此处我们只记录本项目部署过程. 背景介绍 之前已实现gitlab- ...

  2. Docker & k8s 系列二:本机k8s环境搭建

    本篇将会讲解k8s是什么?本机k8s环境搭建,部署一个pod并演示几个kubectl命令,k8s dashboard安装. k8s是什么 k8s是kubernetes的简写,它是一个全新的基于容器技术 ...

  3. Kubernetes【K8S】(二):搭建Kubernetes环境

    系统初始化 设置系统时区 # 设置系统时区为 亚洲/上海 [root@k8s-master01 ~]# timedatectl set-timezone Asia/Shanghai # 设置当前得UT ...

  4. 学习k8s(二)

    kubernetes-国内拉取gcr.io\quay.io镜像方法 方法1: https://hub.docker.com/r/ibmcom/ 例如: gcr.io/google_containers ...

  5. k8s资料转载

    K8S入门(二) kubeadmin单机部署 (kubernetes)k8s入门.yum单机版安装.kuberctl指令.k8s服务实例. kubernetes---CentOS7安装kubernet ...

  6. K8S+GitLab-自动化分布式部署ASP.NET Core(三) 更新镜像版本并部署到K8S上

    一.介绍 前一篇,介绍了ASP.NET Core部署到K8S上,下面介绍我们在发布新一版本中怎么通过Gitlab CI自动给镜像打版本并部署到K8S上. 二.我们通过GitLab CI/CD 变量 不 ...

  7. k8s使用ceph作为后端存储挂载

    一.在ceph集群上操作: 1.创建池(主要使用存储类来进行持久卷的挂载,其他的挂载方式不好使也太麻烦):ceph osd pool create k8s 64 二.在k8s上操作: 1.安装客户端( ...

  8. K8S+GitLab+.net core-自动化分布式部署-3

    K8S+GitLab-自动化分布式部署ASP.NET Core(三) 更新镜像版本并部署到K8S上   一.介绍 前一篇,介绍了ASP.NET Core部署到K8S上,下面介绍我们在发布新一版本中怎么 ...

  9. python安装二进制k8s 1.11.0 一个master、一个node 查看node节点是主机名---apiserver无法启动,后来改了脚本应该可以

    一.脚本说明: 本实验中master.node.etcd都是单体. 安装顺序为:先安装test1节点主要组件,然后开始安装test2节点,最后回头把test1节点加入集群中,这样做目的是理解以后扩容都 ...

随机推荐

  1. springboot项目创建,及运行

    1. File --> new --> spring Initializr(选择jdk,和默认的url)-->next-->通过dubbo调用的服务可以直接下一步,也可以选择w ...

  2. Jenkins自动化部署入门详细教程

    大纲 1.背景 在实际开发中,我们经常要一边开发一边测试,当然这里说的测试并不是程序员对自己代码的单元测试,而是同组程序员将代码提交后,由测试人员测试: 或者前后端分离后,经常会修改接口,然后重新部署 ...

  3. Ride to Office

    [题目描述] 起点与终点相隔4500米.现Charley需要从起点骑车到终点.但是,他有个习惯,沿途需要有人陪伴,即以相同的速度,与另外一个人一起骑.而当他遇到以更快的速度骑车的人时,他会以相应的速度 ...

  4. 线性代数笔记24——微分方程和exp(At)

    原文:https://mp.weixin.qq.com/s/COpYKxQDMhqJRuMK2raMKQ 微分方程指含有未知函数及其导数的关系式,解微分方程就是找出未知函数.未知函数是一元函数的,叫常 ...

  5. Codeforces Round #601 (Div. 2)

    传送门 A. Changing Volume 签到. Code /* * Author: heyuhhh * Created Time: 2019/11/19 22:37:33 */ #include ...

  6. MYSQL 命令导出事件、存储过程、触发器

    普通导出某个数据库 mysqldump -u username -p passowrd databasename > file.sql 顺便导出事件 使用 –events 参数 mysqldum ...

  7. 史上最详细配置HTTPS

    HTTP(超文本传输协议),是一个基于请求与响应,无状态的,应用层的协议,常基于TCP/IP协议传输数据,互联网上应用最为广泛的一种网络协议,所有的WWW文件都必须遵守这个标准.设计HTTP的初衷是为 ...

  8. 2019 SDN上机第6次作业

    2019 SDN上机第6次作业 1.实验拓扑 (1)实验拓扑 (2)使用Python脚本完成拓扑搭建 from mininet.topo import Topo from mininet.net im ...

  9. WPF 精修篇 附加属性

    原文:WPF 精修篇 附加属性 微软把DLL都开源了  今天看了一下 很多WPF实现内容都在里面 https://referencesource.microsoft.com/ 说附加属性 附加属性 是 ...

  10. js的事件循环(Event Loop)

    (本文从掘金小册整理) 首先介绍一下几个概念 进程与线程 相信大家经常会听到 JS 是单线程执行的,但是你是否疑惑过什么是线程? 讲到线程,那么肯定也得说一下进程.本质上来说,两个名词都是 CPU 工 ...