pod 本质是一组并置的容器,代表了Kubemetes 中的基本构建模块。在实际应用中我们并不会单独部署容器, 更多的是针对pod 的容器进行部署和操作。然而这并不意味着一个pod 总是要包含多个容器一一有的实际上只包含一个,单独容器的pod也是非常常见的。值得注意的是,当一个pod 包含多个容器时,这些容器总是运行于同一个工作节点上一一一个pod 绝不会跨越多个工作节点。

03.了解kubernetes pod - 图1

了解pod

由于一个pod 中的所有容器都在相同的network 和UTS 命名空间下运行,所以它们都共享相同的主机名和网络接口。同样这些容器也都在相同的IPC 命名空间下运行,因此能够通过IPC 进行通信。在最新的Kubemetes 和Docker 版本中,它们也能够共享相同的PID 命名空间。但当涉及文件系统时,情况就有所不同。由于大多数容器的文件系统来自容器镜像,因此默认情况下,每个容器的文件系统与其他容器完全隔离。但我们可以使用名为Volume 的Kubemetes 资源来共享文件目录。

03.了解kubernetes pod - 图2

决定何时在pod 中使用多个容器

回顾一下容器应该如何分组到pod 中: 当决定是将两个容器放入一个pod 还是两个单独的pod 时,我们需要问自己以下问题:

  • 它们需要一起运行还是可以在不同的主机上运行?
  • 它们代表的是一个整体还是相互独立的组件?
  • 它们必须一起进行扩缩容还是可以分别进行?

基本上,我们总是应该倾向于在单独的pod中运行容器,除非有特定的原因要求它们是同一pod的一部分。

03.了解kubernetes pod - 图3

pod 定义的主要部分

我们将使用带有-o yaml 选项的kubectl get 命令来获取
pod 的整个YAML 定义,正如下面的代码清单所示。

  1. [root@master01 ~]# kubectl get pod
  2. NAME READY STATUS RESTARTS AGE
  3. nginx-5c559d5697-zt6q7 1/1 Running 0 12s
  4. [root@master01 ~]# kubectl get pod nginx-5c559d5697-zt6q7 -o yaml
  5. apiVersion: v1
  6. kind: Pod
  7. metadata:
  8. annotations:
  9. cni.projectcalico.org/podIP: 10.244.186.197/32
  10. cni.projectcalico.org/podIPs: 10.244.186.197/32
  11. creationTimestamp: "2020-01-08T14:21:51Z"
  12. generateName: nginx-5c559d5697-
  13. labels:
  14. app: nginx
  15. pod-template-hash: 5c559d5697
  16. name: nginx-5c559d5697-zt6q7
  17. namespace: default
  18. ownerReferences:
  19. - apiVersion: apps/v1
  20. blockOwnerDeletion: true
  21. controller: true
  22. kind: ReplicaSet
  23. name: nginx-5c559d5697
  24. uid: bca56ac8-d502-4f69-bdf4-f10ec08dd79c
  25. resourceVersion: "25703"
  26. selfLink: /api/v1/namespaces/default/pods/nginx-5c559d5697-zt6q7
  27. uid: a5915882-8fb2-4bec-b8e1-2ea1cdc0b9fb
  28. spec:
  29. containers:
  30. - image: nginx:alpine
  31. imagePullPolicy: IfNotPresent
  32. name: nginx
  33. ports:
  34. - containerPort: 80
  35. protocol: TCP
  36. resources: {}
  37. terminationMessagePath: /dev/termination-log
  38. terminationMessagePolicy: File
  39. volumeMounts:
  40. - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
  41. name: default-token-q49sn
  42. readOnly: true
  43. dnsPolicy: ClusterFirst
  44. enableServiceLinks: true
  45. nodeName: node03
  46. priority: 0
  47. restartPolicy: Always
  48. schedulerName: default-scheduler
  49. securityContext: {}
  50. serviceAccount: default
  51. serviceAccountName: default
  52. terminationGracePeriodSeconds: 30
  53. tolerations:
  54. - effect: NoExecute
  55. key: node.kubernetes.io/not-ready
  56. operator: Exists
  57. tolerationSeconds: 300
  58. - effect: NoExecute
  59. key: node.kubernetes.io/unreachable
  60. operator: Exists
  61. tolerationSeconds: 300
  62. volumes:
  63. - name: default-token-q49sn
  64. secret:
  65. defaultMode: 420
  66. secretName: default-token-q49sn
  67. status:
  68. conditions:
  69. - lastProbeTime: null
  70. lastTransitionTime: "2020-01-08T14:21:51Z"
  71. status: "True"
  72. type: Initialized
  73. - lastProbeTime: null
  74. lastTransitionTime: "2020-01-08T14:21:53Z"
  75. status: "True"
  76. type: Ready
  77. - lastProbeTime: null
  78. lastTransitionTime: "2020-01-08T14:21:53Z"
  79. status: "True"
  80. type: ContainersReady
  81. - lastProbeTime: null
  82. lastTransitionTime: "2020-01-08T14:21:51Z"
  83. status: "True"
  84. type: PodScheduled
  85. containerStatuses:
  86. - containerID: docker://90148dbe7204ed81e2a8a450d3df923bf77fc1c2f96f1456bfd3a0726e72f48a
  87. image: nginx:alpine
  88. imageID: docker-pullable://nginx@sha256:0e61b143db3110f3b8ae29a67f107d5536b71a7c1f10afb14d4228711fc65a13
  89. lastState: {}
  90. name: nginx
  91. ready: true
  92. restartCount: 0
  93. started: true
  94. state:
  95. running:
  96. startedAt: "2020-01-08T14:21:53Z"
  97. hostIP: 192.168.33.203
  98. phase: Running
  99. podIP: 10.244.186.197
  100. podIPs:
  101. - ip: 10.244.186.197
  102. qosClass: BestEffort
  103. startTime: "2020-01-08T14:21:51Z"

pod 定义由这么几个部分组成: 首先是yaml中使用的Kubernetes API版本和YAML 描述的kind资源类型;所有Kubernetes资源中都可以找到的五大大重要部分:

  • apiVersion 使用的Kubernetes API版本
  • kind 资源类型
  • metadata 包括名称、命名空间、标签和关于该容器的其他信息。
  • spec 包含pod 内容的实际说明, 例如pod 的容器、卷和其他据。
  • status 包含运行中的pod 的当前信息,例如pod 所处的条件、每个容器的描述和状态,以及内部IP和其他基本信息,但是创建时不需要定义。

YAML 基础

它的基本语法规则如下:

  1. 大小写敏感
  2. 使用缩进表示层级关系
  3. 缩进时不允许使用Tab键,只允许使用空格。
  4. 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  5. # 表示注释,从这个字符一直到行尾,都会被解析器忽略

在kubernetes 中,只需要两种结构类型:

  1. Lists
  2. Maps

Maps

Map 是字典,就是一个key:value的键值对

apiVersion: v1
kind: Pod
metadata:
  name: demo-pod
  labels:
    app: myapp
...

YAML 文件转换成 JSON 格式就是

{
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {
        "name": "demo-pod",
        "labels": {
            "app": "myapp"
        }
    }
}

Lists

Lists 就是列表,说白了就是数组

args
  - Cat
  - Dog
  - Fish

对应的 JSON 格式如下

{
    "args": [ 'Cat', 'Dog', 'Fish' ]
}

list 的子项也可以是 Maps,Maps 的子项也可以是list如下所示

apiVersion: v1
kind: Pod
metadata:
  name: demo-pod
  labels:
    app: myapp
spec:
  containers:
    - name: front-end
      image: nginx
      ports:
        - containerPort: 80
    - name: flaskapp-demo
      image: jcdemo/flaskapp
      ports:
        - containerPort: 5000

转成如下 JSON 格式文件

{
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {
        "name": "demo-pod",
        "labels": {
            "app": myapp"
        }
    },
    "spec": {
        "containers": [{
            "name": "front-end",
            "image": "nginx",
            "ports": [{
                "containerPort": "80"
            }]
        }, {
            "name": "flaskapp-demo",
            "image": "jcdemo/flaskapp",
            "ports": [{
                "containerPort": "5000"
            }]
        }]
    }
}

创建 Pod

apiVersion: v1
kind: Pod
metadata:
  name: demo-pod
  namespace: default
  labels:
    app: myapp
    type: pod
spec:
  containers:
  - name: myapp
    image: ikubernetes/myapp:v1
    ports:
    - name: http
      containerPort: 80
  - name: busybox
    image: busybox:latest
    command:
    - "/bin/sh"
    - "-c"
    - "mkdir -p /usr/share/nginx/html; echo $(date) >> /usr/share/nginx/html/test.html;sleep 3600"

pod yaml详解

yaml格式的pod完整内容

apiVersion: v1                    #必选,版本号,例如v1,版本号必须可以用 kubectl api-versions 查询到
kind: Pod                      #必选,Pod
metadata:                      #必选,元数据
  name: string                    #必选,Pod名称
  namespace: string               #必选,Pod所属的命名空间,默认为"default"
  labels:                       #自定义标签
    - name: string                 #自定义标签名字
  annotations:                           #自定义注释列表
    - name: string
spec:                            #必选,Pod中容器的详细定义
  containers:                       #必选,Pod中容器列表
  - name: string                        #必选,容器名称,需符合RFC 1035规范
    image: string                       #必选,容器的镜像名称
    imagePullPolicy: [ Always|Never|IfNotPresent ]  #获取镜像的策略 Alawys表示下载镜像 IfnotPresent表示优先使用本地镜像,否则下载镜像,Nerver表示仅使用本地镜像
    command: [string]               #容器的启动命令列表,如不指定,使用打包时使用的启动命令
    args: [string]                     #容器的启动命令参数列表
    workingDir: string                     #容器的工作目录
    volumeMounts:                 #挂载到容器内部的存储卷配置
    - name: string                 #引用pod定义的共享存储卷的名称,需用volumes[]部分定义的的卷名
      mountPath: string                 #存储卷在容器内mount的绝对路径,应少于512字符
      readOnly: boolean                 #是否为只读模式
    ports:                      #需要暴露的端口库号列表
    - name: string                 #端口的名称
      containerPort: int                #容器需要监听的端口号
      hostPort: int                    #容器所在主机需要监听的端口号,默认与Container相同
      protocol: string                  #端口协议,支持TCP和UDP,默认TCP
    env:                          #容器运行前需设置的环境变量列表
    - name: string                    #环境变量名称
      value: string                   #环境变量的值
    resources:                          #资源限制和请求的设置
      limits:                       #资源限制的设置
        cpu: string                   #Cpu的限制,单位为core数,将用于docker run --cpu-shares参数
        memory: string                  #内存限制,单位可以为Mib/Gib,将用于docker run --memory参数
      requests:                         #资源请求的设置
        cpu: string                   #Cpu请求,容器启动的初始可用数量
        memory: string                    #内存请求,容器启动的初始可用数量
    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
    restartPolicy: [Always | Never | OnFailure] #Pod的重启策略,Always表示一旦不管以何种方式终止运行,kubelet都将重启,OnFailure表示只有Pod以非0退出码退出才重启,Nerver表示不再重启该Pod
    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的目录
      secret:                 #类型为secret的存储卷,挂载集群与定义的secre对象到容器内部
        scretname: string  
        items:     
        - key: string
          path: string
      configMap:                      #类型为configMap的存储卷,挂载预定义的configMap对象到容器内部
        name: string
        items:
        - key: string
          path: string

一个最简单的YAML描述文件

03.了解kubernetes pod - 图4

该文件遵循Kubernetes API 的v1版本。我们描述的资源类型是Pod,名称为kubia-manual : 该pod 由基于luksa/kubia镜像的单个容器组成。此外我们还给该容器命名kubia,并表示它正在监昕8080 端口。

使用kubectl explain来发现API对象字段

[root@master01 ~]# kubectl explain pod
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion    <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/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's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec    <Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

   status    <Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

Kubectl 打印出对象的解释并列出对象可以包含的属性,已经指明了pod的apiversion为v1,kind为Pod,接下来就可以深入了解metadata,spec属性的更多信息。

[root@master01 ~]# kubectl explain pod.metadata
KIND:     Pod
VERSION:  v1

RESOURCE: metadata <Object>

DESCRIPTION:
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#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

   clusterName    <string>
     The name of the cluster which the object belongs to. This is used to
     distinguish resources with same name and namespace in different clusters.
     This field is not set anywhere right now and apiserver is going to ignore
     it if set in create or update request.

   creationTimestamp    <string>
     CreationTimestamp is a timestamp representing the server time when this
     object was created. It is not guaranteed to be set in happens-before order
     across separate operations. Clients may not set this value. It is
     represented in RFC3339 form and is in UTC. Populated by the system.
     Read-only. Null for lists. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   deletionGracePeriodSeconds    <integer>
     Number of seconds allowed for this object to gracefully terminate before it
     will be removed from the system. Only set when deletionTimestamp is also
     set. May only be shortened. Read-only.

   deletionTimestamp    <string>
     DeletionTimestamp is RFC 3339 date and time at which this resource will be
     deleted. This field is set by the server when a graceful deletion is
     requested by the user, and is not directly settable by a client. The
     resource is expected to be deleted (no longer visible from resource lists,
     and not reachable by name) after the time in this field, once the
     finalizers list is empty. As long as the finalizers list contains items,
     deletion is blocked. Once the deletionTimestamp is set, this value may not
     be unset or be set further into the future, although it may be shortened or
     the resource may be deleted prior to this time. For example, a user may
     request that a pod is deleted in 30 seconds. The Kubelet will react by
     sending a graceful termination signal to the containers in the pod. After
     that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL)
     to the container and after cleanup, remove the pod from the API. In the
     presence of network partitions, this object may still exist after this
     timestamp, until an administrator or automated process can determine the
     resource is fully terminated. If not set, graceful deletion of the object
     has not been requested. Populated by the system when a graceful deletion is
     requested. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   finalizers    <[]string>
     Must be empty before the object is deleted from the registry. Each entry is
     an identifier for the responsible component that will remove the entry from
     the list. If the deletionTimestamp of the object is non-nil, entries in
     this list can only be removed.

   generateName    <string>
     GenerateName is an optional prefix, used by the server, to generate a
     unique name ONLY IF the Name field has not been provided. If this field is
     used, the name returned to the client will be different than the name
     passed. This value will also be combined with a unique suffix. The provided
     value has the same validation rules as the Name field, and may be truncated
     by the length of the suffix required to make the value unique on the
     server. If this field is specified and the generated name exists, the
     server will NOT return a 409 - instead, it will either return 201 Created
     or 500 with Reason ServerTimeout indicating a unique name could not be
     found in the time allotted, and the client should retry (optionally after
     the time indicated in the Retry-After header). Applied only if Name is not
     specified. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency

   generation    <integer>
     A sequence number representing a specific generation of the desired state.
     Populated by the system. Read-only.

   labels    <map[string]string>
     Map of string keys and values that can be used to organize and categorize
     (scope and select) objects. May match selectors of replication controllers
     and services. More info: http://kubernetes.io/docs/user-guide/labels

   managedFields    <[]Object>
     ManagedFields maps workflow-id and version to the set of fields that are
     managed by that workflow. This is mostly for internal housekeeping, and
     users typically shouldn't need to set or understand this field. A workflow
     can be the user's name, a controller's name, or the name of a specific
     apply path like "ci-cd". The set of fields is always in the version that
     the workflow used when modifying the object.

   name    <string>
     Name must be unique within a namespace. Is required when creating
     resources, although some resources may allow a client to request the
     generation of an appropriate name automatically. Name is primarily intended
     for creation idempotence and configuration definition. Cannot be updated.
     More info: http://kubernetes.io/docs/user-guide/identifiers#names

   namespace    <string>
     Namespace defines the space within each name must be unique. An empty
     namespace is equivalent to the "default" namespace, but "default" is the
     canonical representation. Not all objects are required to be scoped to a
     namespace - the value of this field for those objects will be empty. Must
     be a DNS_LABEL. Cannot be updated. More info:
     http://kubernetes.io/docs/user-guide/namespaces

   ownerReferences    <[]Object>
     List of objects depended by this object. If ALL objects in the list have
     been deleted, this object will be garbage collected. If this object is
     managed by a controller, then an entry in this list will point to this
     controller, with the controller field set to true. There cannot be more
     than one managing controller.

   resourceVersion    <string>
     An opaque value that represents the internal version of this object that
     can be used by clients to determine when objects have changed. May be used
     for optimistic concurrency, change detection, and the watch operation on a
     resource or set of resources. Clients must treat these values as opaque and
     passed unmodified back to the server. They may only be valid for a
     particular resource or set of resources. Populated by the system.
     Read-only. Value must be treated as opaque by clients and . More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency

   selfLink    <string>
     SelfLink is a URL representing this object. Populated by the system.
     Read-only. DEPRECATED Kubernetes will stop propagating this field in 1.20
     release and the field is planned to be removed in 1.21 release.

   uid    <string>
     UID is the unique in time and space value for this object. It is typically
     generated by the server on successful creation of a resource and is not
     allowed to change on PUT operations. Populated by the system. Read-only.
     More info: http://kubernetes.io/docs/user-guide/identifiers#uids
[root@master01 ~]# kubectl explain pod.spec
KIND:     Pod
VERSION:  v1

RESOURCE: spec <Object>

DESCRIPTION:
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

     PodSpec is a description of a pod.

FIELDS:
   activeDeadlineSeconds    <integer>
     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.

   affinity    <Object>
     If specified, the pod's scheduling constraints

   automountServiceAccountToken    <boolean>
     AutomountServiceAccountToken indicates whether a service account token
     should be automatically mounted.

   containers    <[]Object> -required-
     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是spec中必须要有的,可以继续查看 containers的信息,其他字段也是一样

[root@master01 ~]# kubectl explain pod.spec.containers
KIND:     Pod
VERSION:  v1

RESOURCE: containers <[]Object>

DESCRIPTION:
     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.

     A single application container that you want to run within a pod.

FIELDS:
   args    <[]string>
     Arguments to the entrypoint. The docker image's CMD is used if this is not
     provided. Variable references $(VAR_NAME) are expanded using the
     container's environment. If a variable cannot be resolved, the reference in
     the input string will be unchanged. The $(VAR_NAME) syntax can be escaped
     with a double $$, ie: $$(VAR_NAME). Escaped references will never be
     expanded, regardless of whether the variable exists or not. Cannot be
     updated. More info:
     https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell

   command    <[]string>
     Entrypoint array. Not executed within a shell. The docker image's
     ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME)
     are expanded using the container's environment. If a variable cannot be
     resolved, the reference in the input string will be unchanged. The
     $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME).
     Escaped references will never be expanded, regardless of whether the
     variable exists or not. Cannot be updated. More info:
     https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell

   env    <[]Object>
     List of environment variables to set in the container. Cannot be updated.

   envFrom    <[]Object>
     List of sources to populate environment variables in the container. The
     keys defined within a source must be a C_IDENTIFIER. All invalid keys will
     be reported as an event when the container is starting. When a key exists
     in multiple sources, the value associated with the last source will take
     precedence. Values defined by an Env with a duplicate key will take
     precedence. Cannot be updated.

   image    <string>
     Docker image name. More info:
     https://kubernetes.io/docs/concepts/containers/images This field is
     optional to allow higher level config management to default or override
     container images in workload controllers like Deployments and StatefulSets.

   imagePullPolicy    <string>
     Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always
     if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated.
     More info:
     https://kubernetes.io/docs/concepts/containers/images#updating-images

   lifecycle    <Object>
     Actions that the management system should take in response to container
     lifecycle events. Cannot be updated.

   livenessProbe    <Object>
     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

   name    <string> -required-
     Name of the container specified as a DNS_LABEL. Each container in a pod
     must have a unique name (DNS_LABEL). Cannot be updated.

   ports    <[]Object>
     List of ports to expose from the container. Exposing a port here gives the
     system additional information about the network connections a container
     uses, but is primarily informational. Not specifying a port here DOES NOT
     prevent that port from being exposed. Any port which is listening on the
     default "0.0.0.0" address inside a container will be accessible from the
     network. Cannot be updated.

   readinessProbe    <Object>
     Periodic probe of container service readiness. Container will be removed
     from service endpoints if the probe fails. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

   resources    <Object>
     Compute Resources required by this container. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/

   securityContext    <Object>
     Security options the pod should run with. More info:
     https://kubernetes.io/docs/concepts/policy/security-context/ More info:
     https://kubernetes.io/docs/tasks/configure-pod-container/security-context/

   startupProbe    <Object>
     StartupProbe indicates that the Pod has successfully initialized. If
     specified, no other probes are executed until this completes successfully.
     If this probe fails, the Pod will be restarted, just as if the
     livenessProbe failed. This can be used to provide different probe
     parameters at the beginning of a Pod's lifecycle, when it might take a long
     time to load data or warm a cache, than during steady-state operation. This
     cannot be updated. This is an alpha feature enabled by the StartupProbe
     feature flag. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

   stdin    <boolean>
     Whether this container should allocate a buffer for stdin in the container
     runtime. If this is not set, reads from stdin in the container will always
     result in EOF. Default is false.

   stdinOnce    <boolean>
     Whether the container runtime should close the stdin channel after it has
     been opened by a single attach. When stdin is true the stdin stream will
     remain open across multiple attach sessions. If stdinOnce is set to true,
     stdin is opened on container start, is empty until the first client
     attaches to stdin, and then remains open and accepts data until the client
     disconnects, at which time stdin is closed and remains closed until the
     container is restarted. If this flag is false, a container processes that
     reads from stdin will never receive an EOF. Default is false

   terminationMessagePath    <string>
     Optional: Path at which the file to which the container's termination
     message will be written is mounted into the container's filesystem. Message
     written is intended to be brief final status, such as an assertion failure
     message. Will be truncated by the node if greater than 4096 bytes. The
     total message length across all containers will be limited to 12kb.
     Defaults to /dev/termination-log. Cannot be updated.

   terminationMessagePolicy    <string>
     Indicate how the termination message should be populated. File will use the
     contents of terminationMessagePath to populate the container status message
     on both success and failure. FallbackToLogsOnError will use the last chunk
     of container log output if the termination message file is empty and the
     container exited with an error. The log output is limited to 2048 bytes or
     80 lines, whichever is smaller. Defaults to File. Cannot be updated.

   tty    <boolean>
     Whether this container should allocate a TTY for itself, also requires
     'stdin' to be true. Default is false.

   volumeDevices    <[]Object>
     volumeDevices is the list of block devices to be used by the container.
     This is a beta feature.

   volumeMounts    <[]Object>
     Pod volumes to mount into the container's filesystem. Cannot be updated.

   workingDir    <string>
     Container's working directory. If not specified, the container runtime's
     default will be used, which might be configured in the container image.
     Cannot be updated.

name是pod.spec.continers必须要有的

[root@master01 ~]# kubectl explain pod.spec.containers.name
KIND:     Pod
VERSION:  v1

FIELD:    name <string>

DESCRIPTION:
     Name of the container specified as a DNS_LABEL. Each container in a pod
     must have a unique name (DNS_LABEL). Cannot be updated.

创建pod

编写yaml文件

cat>nginx.yaml<<EOF 
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
spec:
  containers:
  - image: nginx
    name: nginx
    ports:
    - containerPort: 80
EOF

加载yaml文件

kubectl apply -f nginx.yaml

得到运行中pod 的完整定义

[root@master01 ~]# kubectl -n default get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-5c559d5697-zt6q7   1/1     Running   0          47m
nginx-pod                1/1     Running   0          46s
[root@master01 ~]# kubectl get pod nginx-pod -o yaml
apiVersion: v1
kind: Pod
metadata:
  annotations:
    cni.projectcalico.org/podIP: 10.244.186.198/32
    cni.projectcalico.org/podIPs: 10.244.186.198/32
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"name":"nginx-pod","namespace":"default"},"spec":{"containers":[{"image":"nginx","name":"nginx","ports":[{"containerPort":80}]}]}}
  creationTimestamp: "2020-01-08T15:08:37Z"
  name: nginx-pod
  namespace: default
  resourceVersion: "31315"
  selfLink: /api/v1/namespaces/default/pods/nginx-pod
  uid: 48f2a023-f70a-4ce2-900a-43f23e1afd46
spec:
  containers:
  - image: nginx
    imagePullPolicy: Always
    name: nginx
    ports:
    - containerPort: 80
      protocol: TCP
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-q49sn
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: node03
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 30
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  volumes:
  - name: default-token-q49sn
    secret:
      defaultMode: 420
      secretName: default-token-q49sn
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2020-01-08T15:08:37Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2020-01-08T15:08:43Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2020-01-08T15:08:43Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2020-01-08T15:08:37Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://fea50cdc2973e36bbd8af4a5341182aa980becf8a3a226aca49d7924433a8b8b
    image: nginx:latest
    imageID: docker-pullable://nginx@sha256:b2d89d0a210398b4d1120b3e3a7672c16a4ba09c2c4a0395f18b9f7999b768f2
    lastState: {}
    name: nginx
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2020-01-08T15:08:42Z"
  hostIP: 192.168.33.203
  phase: Running
  podIP: 10.244.186.198
  podIPs:
  - ip: 10.244.186.198
  qosClass: BestEffort
  startTime: "2020-01-08T15:08:37Z"
[root@master01 ~]# kubectl -n default get pod nginx-pod -o json
{
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {
        "annotations": {
            "cni.projectcalico.org/podIP": "10.244.186.198/32",
            "cni.projectcalico.org/podIPs": "10.244.186.198/32",
            "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"name\":\"nginx-pod\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"image\":\"nginx\",\"name\":\"nginx\",\"ports\":[{\"containerPort\":80}]}]}}\n"
        },
        "creationTimestamp": "2020-01-08T15:08:37Z",
        "name": "nginx-pod",
        "namespace": "default",
        "resourceVersion": "31315",
        "selfLink": "/api/v1/namespaces/default/pods/nginx-pod",
        "uid": "48f2a023-f70a-4ce2-900a-43f23e1afd46"
    },
    "spec": {
        "containers": [
            {
                "image": "nginx",
                "imagePullPolicy": "Always",
                "name": "nginx",
                "ports": [
                    {
                        "containerPort": 80,
                        "protocol": "TCP"
                    }
                ],
                "resources": {},
                "terminationMessagePath": "/dev/termination-log",
                "terminationMessagePolicy": "File",
                "volumeMounts": [
                    {
                        "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
                        "name": "default-token-q49sn",
                        "readOnly": true
                    }
                ]
            }
        ],
        "dnsPolicy": "ClusterFirst",
        "enableServiceLinks": true,
        "nodeName": "node03",
        "priority": 0,
        "restartPolicy": "Always",
        "schedulerName": "default-scheduler",
        "securityContext": {},
        "serviceAccount": "default",
        "serviceAccountName": "default",
        "terminationGracePeriodSeconds": 30,
        "tolerations": [
            {
                "effect": "NoExecute",
                "key": "node.kubernetes.io/not-ready",
                "operator": "Exists",
                "tolerationSeconds": 300
            },
            {
                "effect": "NoExecute",
                "key": "node.kubernetes.io/unreachable",
                "operator": "Exists",
                "tolerationSeconds": 300
            }
        ],
        "volumes": [
            {
                "name": "default-token-q49sn",
                "secret": {
                    "defaultMode": 420,
                    "secretName": "default-token-q49sn"
                }
            }
        ]
    },
    "status": {
        "conditions": [
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2020-01-08T15:08:37Z",
                "status": "True",
                "type": "Initialized"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2020-01-08T15:08:43Z",
                "status": "True",
                "type": "Ready"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2020-01-08T15:08:43Z",
                "status": "True",
                "type": "ContainersReady"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2020-01-08T15:08:37Z",
                "status": "True",
                "type": "PodScheduled"
            }
        ],
        "containerStatuses": [
            {
                "containerID": "docker://fea50cdc2973e36bbd8af4a5341182aa980becf8a3a226aca49d7924433a8b8b",
                "image": "nginx:latest",
                "imageID": "docker-pullable://nginx@sha256:b2d89d0a210398b4d1120b3e3a7672c16a4ba09c2c4a0395f18b9f7999b768f2",
                "lastState": {},
                "name": "nginx",
                "ready": true,
                "restartCount": 0,
                "started": true,
                "state": {
                    "running": {
                        "startedAt": "2020-01-08T15:08:42Z"
                    }
                }
            }
        ],
        "hostIP": "192.168.33.203",
        "phase": "Running",
        "podIP": "10.244.186.198",
        "podIPs": [
            {
                "ip": "10.244.186.198"
            }
        ],
        "qosClass": "BestEffort",
        "startTime": "2020-01-08T15:08:37Z"
    }
}

查看pod

get列表中创建的pod

[root@master01 ~]# kubectl -n default get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-5c559d5697-zt6q7   1/1     Running   0          49m
nginx-pod                1/1     Running   0          2m31s

logs查看pod应用程序日志

[root@master01 ~]# kubectl -n default logs nginx-pod 
10.244.241.64 - - [08/Jan/2020:15:13:21 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:22 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:23 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:24 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:25 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:26 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:27 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:28 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

-f 追踪日志

[root@master01 ~]# kubectl -n default logs -f nginx-pod 
10.244.241.64 - - [08/Jan/2020:15:13:21 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:22 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:23 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:24 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:25 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:26 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:27 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.241.64 - - [08/Jan/2020:15:13:28 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

exec进入pod

[root@master01 ~]# kubectl -n default exec -it  nginx-pod  -- /bin/bash
root@nginx-pod:/#

-c 进入pod中指定容器

[root@master01 ~]# kubectl -n default exec -it  nginx-pod  -c nginx -- /bin/bash
root@nginx-pod:/#

describe查看pod信息

[root@master01 ~]# kubectl describe pod -n default nginx-pod 
Name:         nginx-pod
Namespace:    default
Priority:     0
Node:         node03/192.168.33.203
Start Time:   Wed, 08 Jan 2020 23:08:37 +0800
Labels:       <none>
Annotations:  cni.projectcalico.org/podIP: 10.244.186.198/32
              cni.projectcalico.org/podIPs: 10.244.186.198/32
              kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"name":"nginx-pod","namespace":"default"},"spec":{"containers":[{"image":"ngi...
Status:       Running
IP:           10.244.186.198
IPs:
  IP:  10.244.186.198
Containers:
  nginx:
    Container ID:   docker://fea50cdc2973e36bbd8af4a5341182aa980becf8a3a226aca49d7924433a8b8b
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:b2d89d0a210398b4d1120b3e3a7672c16a4ba09c2c4a0395f18b9f7999b768f2
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Wed, 08 Jan 2020 23:08:42 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-q49sn (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-q49sn:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-q49sn
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:          <none>

删除pod

[root@master01 ~]# kubectl -n default  delete pod nginx-pod 
pod "nginx-pod" deleted