Kerbernetes的Pod资源管理

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: 文章详细介绍了Kubernetes中Pod资源的管理,包括Pod的基本概念、标签(Label)和标签选择器(Label Selector)的使用方法,以及如何通过kubectl命令行工具对Pod资源进行操作和管理。

作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。

一.什么是pod

  同一pod内所有容器使用IPC相互通信,因为它们共享了IPC,UTS,Network;

  容器可以通过本地主机(回环网卡lo接口)找到彼此;

  每个容器都继承pod的名称;

  每个pod在一个平坦的共享网络空间中都有一个IP地址;

  数据卷(Volumes)由pod中的容器共享;  

  温馨提示:  
    一般情况下,建议大家一个pod里只存放一个容器即可,但有时候我们又不得不将多个容器封装在同一个pod中,因为一个进程实现的功能毕竟有限,比如收集Nginx的日志,Nginx会产生大量日志,但是日志收集功能Nginx并不拥有;  
    综上所述,我们可以使用flume或者是filebeat与nginx在同一个pod中,nginx实现反向代理而flume实现日志收集,此时我们说flume只是nginx的辅助工具,专业术语叫边车(side car,还记得抗日剧中的那种边车吗?一个司机拉着4,5个士兵的小车)。

二.标签(Label)

1>.什么是标签(Label)

  标签就是"键值"类型的数据,它们可于资源创建时直接指定,也可随时按需添加于活动对象,而后即可由标签选择器进行匹配度检查从而完成资源挑选。  

  一个对象可拥有不止一个标签,而同一个标签也可被添加至多个资源之上  

  实践中,可用为资源附加多个不同维度的标签以实现灵活的资源分组管理功能,例如版本标签,环境标签,分层架构标签等,用于交叉标识同一个资源所属的不同版本,环境及架构层级等

2>.标签的命名规则

  标签中的键名称通常由键前缀和键名组成,其中键前缀可选,其格式形如"KEY_PREFIX/KEY_NAME"
      键名至多能使用63个字符,可使用字母,数字,连接号(-),下划线(_),点号(.)等字符,且只能以字母或者数字开头;
      
  键前缀必须为DNS子域名格式,且不能超过253个字符。省略键前缀时,键将被视为用户的私有数据,不过由于kubernetes系统组件或第三方组件自动为用户资源添加的键必须使用键前缀,而"kubernetes.io/"前缀预留给核心组件使用;
      
  标签中的键值必须不能多余63个字符,它要么为空,要么是以字母或数字开头及结尾,且中间仅使用了字母,数字,连接号(-),下划线(_)或则点号(.)等字符的数据。

3>.标签选择器(Label Selector)

  标签选择器用于表达标签的查询条件或者选择标准,kubernetes API目前支持两个选择器:
    基于等值关系(equality-based)  
      操作符有"=","==",和"!="三种,其中前两个意义相同,都表示"等值"关系,最后一个表示"不等"关系。  
    基于集合关系(set-based)  
      KEY in(VALUE1,VALUE2,...)  
      KEY not in(VALUE1,VALUE2,...)  
      KEY:  
        所有存在此键名标签的资源。  
      !KEY:  
        和上面相反,及所有不存在此键名的标签的资源。  
  使用标签选择器时还需要遵循以下逻辑:  
    同时指定的多个选择器之间的逻辑关系为"与"操作;  
    使用空值的标签选择器意味着每个资源对象都将被选中;  
    空的标签选择器将无法选出任何资源。

4>.定义标签选择器的方式

  kubernetes的诸多资源对象必须以标签选择器的方式关联到Pod资源对象,例如Service,Deployment和ReplicaSet类型的资源等,它们在spec字段中嵌套使用嵌套的"selector"字段,通过"matchLabels"构造复杂的标签选择机制。

  matchLabels:
    通过直接给定键值对指定标签选择器。

  matchExpressions:  
    基于表达式指定的标签选择器列表,每个选择器形如"{key:KEY_NAME,operator:OPERATOR,values:[VALUE1,VALUE2,...]}",选择器列表间为"逻辑与"关系;  
    使用"In"或者"NotIn"操作符时,其values非必须为非空的字符串列表,而使用"Exists"或者"DostNotExist"时,其values必须为空。

三.标签(Labels)和标签选择器(Label Selector)的基本操作

1>.创建名称空间

[root@master200.yinzhengjie.org.cn ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   38h
kube-node-lease   Active   38h
kube-public       Active   38h
kube-system       Active   38h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create ns develop
namespace/develop created
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   38h
develop           Active   2s
kube-node-lease   Active   38h
kube-public       Active   38h
kube-system       Active   38h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl create ns develop

2>.编写yaml文件

[root@master200.yinzhengjie.org.cn ~]# mkdir -pv /yinzhengjie/data/k8s/manifests/basic
mkdir: created directory ‘/yinzhengjie/data’
mkdir: created directory ‘/yinzhengjie/data/k8s’
mkdir: created directory ‘/yinzhengjie/data/k8s/manifests’
mkdir: created directory ‘/yinzhengjie/data/k8s/manifests/basic’
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: develop
  labels:
    app: pod-demo
    rel: stable
spec:
  containers:
  - name: mynginx
    image: nginx:1.14-alpine
  - name: mybox
    image: busybox:latest
    imagePullPolicy: IfNotPresent
    command: ["/bin/sh","-c","sleep 86400"]
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml

3>.应用yaml文件并查看标签

[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: develop
  labels:
    app: pod-demo
    rel: stable
spec:
  containers:
  - name: mynginx
    image: nginx:1.14-alpine
  - name: mybox
    image: busybox:latest
    imagePullPolicy: IfNotPresent
    command: ["/bin/sh","-c","sleep 86400"]
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide
No resources found in develop namespace.
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml
pod/pod-demo created
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide
NAME       READY   STATUS              RESTARTS   AGE   IP       NODE                         NOMINATED NODE   READINESS GATES
pod-demo   0/2     ContainerCreating   0          2s    <none>   node203.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml

[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide
NAME       READY   STATUS              RESTARTS   AGE   IP       NODE                         NOMINATED NODE   READINESS GATES
pod-demo   0/2     ContainerCreating   0          2s    <none>   node203.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels
NAME       READY   STATUS              RESTARTS   AGE   IP       NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   0/2     ContainerCreating   0          18s   <none>   node203.yinzhengjie.org.cn   <none>           <none>            app=pod-demo,rel=stable
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels

4>.为pod动态添加标签

[root@master200.yinzhengjie.org.cn ~]# kubectl label --help
Update the labels on a resource.

  *  A label key and value must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and
underscores, up to  63 characters each.
  *  Optionally, the key can begin with a DNS subdomain prefix and a single '/', like example.com/my-app
  *  If --overwrite is true, then existing labels can be overwritten, otherwise attempting to overwrite a label will
result in an error.
  *  If --resource-version is specified, then updates will use this resource version, otherwise the existing
resource-version will be used.

Examples:
  # Update pod 'foo' with the label 'unhealthy' and the value 'true'.
  kubectl label pods foo unhealthy=true

  # Update pod 'foo' with the label 'status' and the value 'unhealthy', overwriting any existing value.
  kubectl label --overwrite pods foo status=unhealthy

  # Update all pods in the namespace
  kubectl label pods --all status=unhealthy

  # Update a pod identified by the type and name in "pod.json"
  kubectl label -f pod.json status=unhealthy

  # Update pod 'foo' only if the resource is unchanged from version 1.
  kubectl label pods foo status=unhealthy --resource-version=1

  # Update pod 'foo' by removing a label named 'bar' if it exists.
  # Does not require the --overwrite flag.
  kubectl label pods foo bar-

Options:
      --all=false: Select all resources, including uninitialized ones, in the namespace of the specified resource types
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
      --field-selector='': Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector
key1=value1,key2=value2). The server only supports a limited number of field queries per type.
  -f, --filename=[]: Filename, directory, or URL to files identifying the resource to update the labels
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
      --list=false: If true, display the labels for a given resource.
      --local=false: If true, label will NOT contact api-server but run locally.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --overwrite=false: If true, allow labels to be overwritten, otherwise reject label updates that overwrite existing
labels.
      --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the
command. If set to true, record the command. If not set, default to updating the existing annotation value only if one
already exists.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
      --resource-version='': If non-empty, the labels update will only succeed if this is the current resource-version
for the object. Only valid when specifying a single resource.
  -l, --selector='': Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and
'!='.(e.g. -l key1=value1,key2=value2).
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
Usage:
  kubectl label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
[options]

Use "kubectl options" for a list of global command-line options (applies to all commands).
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl label --help

[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels
NAME       READY   STATUS    RESTARTS   AGE     IP           NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   2/2     Running   0          5m28s   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            app=pod-demo,rel=stable
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl label pods pod-demo -n develop tier=frontend
pod/pod-demo labeled
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels
NAME       READY   STATUS    RESTARTS   AGE     IP           NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   2/2     Running   0          7m11s   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            app=pod-demo,rel=stable,tier=frontend
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl label pods pod-demo -n develop tier=frontend

5>.修改已经存在的标签

[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels
NAME       READY   STATUS    RESTARTS   AGE     IP           NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   2/2     Running   0          9m35s   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            app=pod-demo,rel=stable,tier=frontend
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl label pods pod-demo -n develop app=my-pod --overwrite
pod/pod-demo labeled
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels
NAME       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   2/2     Running   0          10m   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            app=my-pod,rel=stable,tier=frontend
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl label pods pod-demo -n develop app=my-pod --overwrite

6>.为pod动态删除标签

[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels
NAME       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   2/2     Running   0          13m   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            app=my-pod,rel=stable,tier=frontend
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl label pods pod-demo -n develop rel-
pod/pod-demo labeled
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels
NAME       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   2/2     Running   0          13m   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            app=my-pod,tier=frontend
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl label pods pod-demo -n develop rel-

7>.标签过滤器使用案例

[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels
NAME       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   2/2     Running   0          18m   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            app=my-pod,tier=frontend
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels -l app=my              #过滤标签KEY名称"app"对应的值为"my"的pod,很显然,并不能匹配到
No resources found in develop namespace.
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels -l app=my-pod            #同上,过滤KEY名称"app"对应的值为"my-pod"的pod,可以匹配到咱们创建的pod
NAME       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   2/2     Running   0          18m   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            app=my-pod,tier=frontend
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels -l app!=my-pod            #和上面相反,过滤KEY名称"app"对应的值不为"my-pod"的pod
No resources found in develop namespace.
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels -l "app in (my)"          #过滤KYE名称为"app"对应的值为"my"的pod
No resources found in develop namespace.
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide --show-labels -l "app in (my,my-pod)"      #同上,过滤KEY名称为"app"对应的值为"my","my-pod"中任意一个pod
NAME       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   2/2     Running   0          22m   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            app=my-pod,tier=frontend
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide -l "app in (my,my-pod)" -L app          #使用"-L"表示列出"app"对应的属性名称。
NAME       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES   APP
pod-demo   2/2     Running   0          23m   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            my-pod
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide -l "app notin (my,my-pod)"             #和上面相反,过滤KEY名称为"app"对应的值不为"my","my-pod"中的任意一个
No resources found in develop namespace.
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide -l "app"                       #过滤包含KEY名称为"app"的pod,此处我没有加"--show-labels"默认是看不到pod的标签哟~
NAME       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES
pod-demo   2/2     Running   0          24m   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide -l '!app'                      #和上面相反
No resources found in develop namespace.
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide -l "app"  --show-labels
NAME       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES   LABELS
pod-demo   2/2     Running   0          37m   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>            app=my-pod,tier=frontend
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n develop -o wide -l '!app' --show-labels
No resources found in develop namespace.
[root@master200.yinzhengjie.org.cn ~]#

四.资源注解(annotation)

  注解也是"键值"类型的数据,不过它不能用于标签及挑选kubernetes对象(换句话说,虽然注解也是键值对形式存在,但不能被标签选择器过滤,因为标签选择器仅对标签进行过滤),仅用于为资源提供"元数据"信息

  注解中的元数据不受字符数量的限制,它可大可小,可以为结构化或非结构化形式,也支持使用在标签中禁止使用的其它字符

  在kubernetes的新版本中(Alpha或Beta阶段)为某资源引入新字段时,常以主机方式提供以避免其增删等变动给用户带去的困扰,一旦确定支持使用它们,这些新增字段再引入到资源中并淘汰相关的注解。

1>.编辑yaml文件配置有关资源注解的参数

[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.metadata.annotations
KIND:     Pod
VERSION:  v1

FIELD:    annotations <map[string]string>

DESCRIPTION:
     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
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.metadata.annotations

[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# cat /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: develop
  labels:
    app: pod-demo
    rel: stable
  annotations:
    myk8s/project: hello-world
spec:
  containers:
  - name: mynginx
    image: nginx:1.14-alpine
  - name: mybox
    image: busybox:latest
    imagePullPolicy: IfNotPresent
    command: ["/bin/sh","-c","sleep 86400"]
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# vim /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml

2>.应用资源注解

[root@master200.yinzhengjie.org.cn ~]# kubectl describe  pods -n develop | head -15
Name:         pod-demo
Namespace:    develop
Priority:     0
Node:         node203.yinzhengjie.org.cn/172.200.1.203
Start Time:   Thu, 06 Feb 2020 09:59:43 +0800
Labels:       app=my-pod
              tier=frontend
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"labels":{"app":"pod-demo","rel":"stable"},"name":"pod-demo","namespace":"dev...
Status:       Running
IP:           10.244.3.2
IPs:
  IP:  10.244.3.2
Containers:
  mynginx:
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml 
pod/pod-demo configured
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl describe  pods -n develop | head -15
Name:         pod-demo
Namespace:    develop
Priority:     0
Node:         node203.yinzhengjie.org.cn/172.200.1.203
Start Time:   Thu, 06 Feb 2020 09:59:43 +0800
Labels:       app=pod-demo
              rel=stable
              tier=frontend
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{"myk8s/project":"hello-world"},"labels":{"app":"pod-demo","rel":"stable"},"name...
              myk8s/project: hello-world
Status:       Running
IP:           10.244.3.2
IPs:
  IP:  10.244.3.2
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl apply -f /yinzhengjie/data/k8s/manifests/basic/pod-demo.yaml

五.pod的生命周期

initContainers(初始化容器阶段)
  

main container(主容器运行阶段)
  阶段一:容器刚刚创建完成之后
    post start hook
  阶段二:容器正常运行
    livenessProbe(需要做健康状态检查,即验证存活状态检测,当发现容器运行不正常会立即重启,若重启后容器依旧不正常运行会逐一累计间隔时间进行重启)
    readinessProbe(就绪状态检测,即验证服务是否正常运行,如果就绪的话就作为service的后端,如果一直处于未就绪状态就会讲该容器从service的后端移除掉;需要注意的是该步骤也没有权限重启容器,这就是它和健康检查的重要区别)
  阶段三:容器即将结束之前
    pre stop hook

博主推荐阅读:
  https://www.cnblogs.com/yinzhengjie/p/12267371.html

[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.initContainers
KIND:     Pod
VERSION:  v1

RESOURCE: initContainers <[]Object>

DESCRIPTION:
     List of initialization containers belonging to the pod. Init containers are
     executed in order prior to containers being started. If any init container
     fails, the pod is considered to have failed and is handled according to its
     restartPolicy. The name for an init container or normal container must be
     unique among all containers. Init containers may not have Lifecycle
     actions, Readiness probes, Liveness probes, or Startup probes. The
     resourceRequirements of an init container are taken into account during
     scheduling by finding the highest request/limit for each resource type, and
     then using the max of of that value or the sum of the normal containers.
     Limits are applied to init containers in a similar fashion. Init containers
     cannot currently be added or removed. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
     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.

[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.initContainers

[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.lifecycle
KIND:     Pod
VERSION:  v1

RESOURCE: lifecycle <Object>

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

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

FIELDS:
   postStart    <Object>
     PostStart is called immediately after a container is created. If the
     handler fails, the container is terminated and restarted according to its
     restart policy. Other management of the container blocks until the hook
     completes. More info:
     https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks
   preStop    <Object>
     PreStop is called immediately before a container is terminated due to an
     API request or management event such as liveness/startup probe failure,
     preemption, resource contention, etc. The handler is not called if the
     container crashes or exits. The reason for termination is passed to the
     handler. The Pod's termination grace period countdown begins before the
     PreStop hooked is executed. Regardless of the outcome of the handler, the
     container will eventually terminate within the Pod's termination grace
     period. Other management of the container blocks until the hook completes
     or until the termination grace period is reached. More info:
     https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.lifecycle

[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.readinessProbe
KIND:     Pod
VERSION:  v1

RESOURCE: readinessProbe <Object>

DESCRIPTION:
     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
     Probe describes a health check to be performed against a container to
     determine whether it is alive or ready to receive traffic.

FIELDS:
   exec    <Object>
     One and only one of the following should be specified. Exec specifies the
     action to take.

   failureThreshold    <integer>
     Minimum consecutive failures for the probe to be considered failed after
     having succeeded. Defaults to 3. Minimum value is 1.

   httpGet    <Object>
     HTTPGet specifies the http request to perform.

   initialDelaySeconds    <integer>
     Number of seconds after the container has started before liveness probes
     are initiated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
   periodSeconds    <integer>
     How often (in seconds) to perform the probe. Default to 10 seconds. Minimum
     value is 1.

   successThreshold    <integer>
     Minimum consecutive successes for the probe to be considered successful
     after having failed. Defaults to 1. Must be 1 for liveness and startup.
     Minimum value is 1.

   tcpSocket    <Object>
     TCPSocket specifies an action involving a TCP port. TCP hooks not yet
     supported

   timeoutSeconds    <integer>
     Number of seconds after which the probe times out. Defaults to 1 second.
     Minimum value is 1. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.readinessProbe

[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.livenessProbe
KIND:     Pod
VERSION:  v1

RESOURCE: livenessProbe <Object>

DESCRIPTION:
     Periodic probe of container liveness. Container will be restarted if the
     probe fails. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
     Probe describes a health check to be performed against a container to
     determine whether it is alive or ready to receive traffic.

FIELDS:
   exec    <Object>
     One and only one of the following should be specified. Exec specifies the
     action to take.

   failureThreshold    <integer>
     Minimum consecutive failures for the probe to be considered failed after
     having succeeded. Defaults to 3. Minimum value is 1.

   httpGet    <Object>
     HTTPGet specifies the http request to perform.

   initialDelaySeconds    <integer>
     Number of seconds after the container has started before liveness probes
     are initiated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
   periodSeconds    <integer>
     How often (in seconds) to perform the probe. Default to 10 seconds. Minimum
     value is 1.

   successThreshold    <integer>
     Minimum consecutive successes for the probe to be considered successful
     after having failed. Defaults to 1. Must be 1 for liveness and startup.
     Minimum value is 1.

   tcpSocket    <Object>
     TCPSocket specifies an action involving a TCP port. TCP hooks not yet
     supported

   timeoutSeconds    <integer>
     Number of seconds after which the probe times out. Defaults to 1 second.
     Minimum value is 1. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
[root@master200.yinzhengjie.org.cn ~]#

[root@master200.yinzhengjie.org.cn ~]# kubectl explain pods.spec.containers.livenessProbe

目录
相关文章
|
3月前
|
Kubernetes 应用服务中间件 开发工具
Kerbernetes的Ingress资源管理
关于如何在Kubernetes集群中部署和管理Ingress资源,包括使用Ingress-nginx、配置SSL/TLS以及通过Ingress反向代理Tomcat的实战案例。
37 3
Kerbernetes的Ingress资源管理
|
3月前
|
Kubernetes 负载均衡 开发工具
Kerbernetes的Service资源管理
本文介绍了Kubernetes中Service资源的管理和使用,包括Service的基本概念、代理模型、资源类型、以及如何通过Service实现服务发现和负载均衡。
41 2
Kerbernetes的Service资源管理
|
3月前
|
Kubernetes 安全 网络性能优化
Kerbernetes的Pod资源管理进阶
文章详细介绍了Kubernetes中Pod的资源管理,包括健康检查、资源限制、安全配置、优先级和服务质量类别等方面的进阶知识。
40 0
|
4月前
|
机器学习/深度学习 数据采集 算法框架/工具
使用Python实现深度学习模型:智能人力资源管理与招聘
【8月更文挑战第12天】 使用Python实现深度学习模型:智能人力资源管理与招聘
112 2
|
5月前
|
数据采集 监控 数据安全/隐私保护
ERP系统中的人力资源管理与员工绩效评估解析
【7月更文挑战第25天】 ERP系统中的人力资源管理与员工绩效评估解析
329 1
|
5月前
|
机器学习/深度学习 Oracle 安全
人力资源管理革新:6款系统一站式解决HR事务
**Zoho People、BambooHR、Workday、ADP Workforce Now和Oracle HCM Cloud是知名的人力资源管理系统。Zoho People提供模块化设计、移动应用和自动化工作流;BambooHR以用户友好界面和员工档案管理见长;Workday侧重全球化云解决方案和智能决策工具;ADP Workforce Now集成HR与薪资管理,强调合规性;Oracle HCM Cloud则以高度定制和分析工具闻名。这些系统各有特点,适用于不同规模和需求的企业。**
84 11
|
5月前
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp的人力资源管理系统附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp的人力资源管理系统附带文章源码部署视频讲解等
50 2
|
6月前
|
机器学习/深度学习 人工智能 搜索推荐
人力资源管理(HRM)系统的未来:技术引领的变革浪潮
【6月更文挑战第24天】随着AI、大数据、云计算和移动技术的融合,HRM正转型为提升效率和员工体验的关键工具。AI助力智能决策,大数据驱动精准管理,云计算与移动技术实现无缝访问和远程操作。员工体验被置于设计核心,系统更人性化、个性化。未来趋势强调全面整合与协同工作,赋能企业高效运营。
|
6月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue的人力资源管理系统的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue的人力资源管理系统的详细设计和实现(源码+lw+部署文档+讲解等)
87 8
|
6月前
|
JavaScript Java 测试技术
基于ssm+vue.js+uniapp小程序的中小企业人力资源管理系统附带文章和源代码部署视频讲解等
基于ssm+vue.js+uniapp小程序的中小企业人力资源管理系统附带文章和源代码部署视频讲解等
47 1

热门文章

最新文章

下一篇
无影云桌面