yaml介绍
apiVersion: v1 APIserver 的版本 kind: Pod 资源类型 metadata: 元数据定义 name: pod-demo 元数据资源名字 labels: 定义标签 app: myapp 两个标签 tier: frontend spec: 容器期望状态定义 containers: pod 定义 - name: myapp pod名称 image: ikubernetes/myapp:v1 镜像的版本及路径 - name: busyboxa pod 名称 image: busybox:latest 镜像名称 imagePullPolicy: IfNotPresent #获取镜像的方式 ports: 端口暴露定义 - name: http pod 的容器name - containerPort: 80 容器端口 command: 修改默认运行的命令 - "/bin/sh" - "-c" - "sleep 36000"
pod定义帮助
[root@master manifests]# kubectl explain pods.spec.container 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> 获取镜像的方法 镜像标签是latest默认获取的方式Always表示总是去下载,Never表示本地有就用,本地没有也不去仓库下载,IfNotPresent本地有就用本地的,本地没有就去仓库下载 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/ 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.
pod的端口暴露操作;生明信息
[root@master manifests]# kubectl explain pods.spec.containers.ports KIND: Pod VERSION: v1 RESOURCE: ports <[]Object> DESCRIPTION: 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. ContainerPort represents a network port in a single container. FIELDS: containerPort <integer> -required- pod容器端口 Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536. hostIP <string> 节点IP,建议写成0.0.0.0 What host IP to bind the external port to. hostPort <integer> 节点上的那个端口 Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this. name <string> 端口名称,server中可以引用名称 If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services. protocol <string> 协议默认TCP Protocol for port. Must be UDP, TCP, or SCTP. Defaults to "TCP".
修改默认pod运行得到命令
[root@master manifests]# kubectl explain pods.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>#作为参数传递给comment,如果没给就把容器镜像制作时的CMD指定的做为参数传递给comment 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>#此处命令默认不会运行在shll中的,如果想要运行shll里必须指定;如果没有指定的话,就运行docker镜像制作时指定的ENTRYPOINT 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
官方文档参考地址:https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/
Description | Docker field name | Kubernetes field name |
---|---|---|
The command run by the container | Entrypoint | command |
The arguments passed to the command | Cmd | args |
当您覆盖默认的Entrypoint和Cmd时,这些规则适用:
-
如果您不提供Container
command
或args
使用Container,则使用Docker镜像中定义的默认值。 -
如果为Container提供
command
但不args
提供,则仅使用提供command
的。默认的EntryPoint和Docker镜像中定义的默认Cmd将被忽略。 -
如果仅为
args
Container提供,则Docker镜像中定义的默认入口点将与args
您提供的一起运行。 -
如果提供
command
和args
,则默认的入口点和Docker镜像中定义的默认Cmd将被忽略。你command
和你一起跑args
图像输入点 | 图像Cmd | 集装箱指挥 | 集装箱args | 命令运行 |
---|---|---|---|---|
[/ep-1] |
[foo bar] |
<未设置> | <未设置> | [ep-1 foo bar] |
[/ep-1] |
[foo bar] |
[/ep-2] |
<未设置> | [ep-2] |
[/ep-1] |
[foo bar] |
<未设置> | [zoo boo] |
[ep-1 zoo boo] |
[/ep-1] |
[foo bar] |
[/ep-2] |
[zoo boo] |
[ep-2 zoo boo] |
元数据标签的定义帮助
[root@master manifests]# kubectl explain pods.metadata.labels KIND: Pod VERSION: v1 FIELD: labels <map[string]string> DESCRIPTION: 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
例子
apiVersion: v1 kind: Pod metadata: name: label-demo labels: environment: production app: nginx spec: containers: - name: nginx image: nginx:1.7.9 ports: - containerPort: 80
删除使用yaml创建的pod
[root@master manifests]# kubectl delete -f pod.demo.yaml pod "pod-demo" deleted
查看
[root@master manifests]# kubectl get pods NAME READY STATUS RESTARTS AGE myapp-84cd4b7f95-g6ldp 1/1 Running 3 9d nginx-5896f46c8-zblcs 1/1 Running 3 9d
创建操作
[root@master manifests]# kubectl create -f pod.demo.yaml pod/pod-demo created
查看pods的标签
[root@master manifests]# kubectl get pods --show-labels NAME READY STATUS RESTARTS AGE LABELS myapp-84cd4b7f95-g6ldp 1/1 Running 3 9d pod-template-hash=84cd4b7f95,run=myapp nginx-5896f46c8-zblcs 1/1 Running 3 9d pod-template-hash=5896f46c8,run=nginx pod-demo 2/2 Running 0 3m58s app=myapp,tier=frontend
查看过滤的pods的标签,显示用于app标签值的pod
[root@master manifests]# kubectl get pods -L app NAME READY STATUS RESTARTS AGE APP myapp-84cd4b7f95-g6ldp 1/1 Running 3 9d nginx-5896f46c8-zblcs 1/1 Running 3 9d pod-demo 2/2 Running 0 6m23s myapp
查看过滤指定标签的pods
[root@master manifests]# kubectl get pods -l app dNAME READY STATUS RESTARTS AGE pod-demo 2/2 Running 0 9m30s
查看仔细类型的
[root@master manifests]# kubectl get pods -l app --show-labels NAME READY STATUS RESTARTS AGE LABELS pod-demo 2/2 Running 0 11m app=myapp,tier=frontend
新加资源标签
[root@master manifests]# kubectl label pods pod-demo chenxi=cx pod/pod-demo labeled [root@master manifests]# kubectl get pods -l chenxi,app --show-labels NAME READY STATUS RESTARTS AGE LABELS pod-demo 2/2 Running 0 14m app=myapp,chenxi=cx,tier=frontend
修改资源标签
[root@master manifests]# kubectl label pods pod-demo chenxi=hgf --overwrite pod/pod-demo labeled [root@master manifests]# kubectl get pods -l chenxi,app --show-labels NAME READY STATUS RESTARTS AGE LABELS pod-demo 2/2 Running 0 17m app=myapp,chenxi=hgf,tier=frontend
标签选择器的使用;等值类的使用
[root@master manifests]# kubectl get pods -l app=myapp --show-labels #表示显示app标签等于myapp NAME READY STATUS RESTARTS AGE LABELS pod-demo 2/2 Running 0 20m app=myapp,chenxi=hgf,tier=frontend [root@master manifests]# kubectl get pods -l app=myapp,chenxi!=cx --show-labels 显示app标签等于myapp并且chenxi标签值不等于cx的pod NAME READY STATUS RESTARTS AGE LABELS pod-demo 2/2 Running 0 20m app=myapp,chenxi=hgf,tier=frontend
选择集合关系,值等于cx或者hgf的pods
[root@master manifests]# kubectl label pods nginx-5896f46c8-zblcs chenxi=hgf pod/nginx-5896f46c8-zblcs labeled [root@master manifests]# kubectl get pods -l "chenxi,app" NAME READY STATUS RESTARTS AGE pod-demo 2/2 Running 0 27m [root@master manifests]# kubectl label pods nginx-5896f46c8-zblcs chenxi=cx --overwrite pod/nginx-5896f46c8-zblcs labeled [root@master manifests]# kubectl get pods -l "chenxi in (cx,hgf)" NAME READY STATUS RESTARTS AGE nginx-5896f46c8-zblcs 1/1 Running 3 9d pod-demo 2/2 Running 0 29m
值不等于cx或者hgf的pods
[root@master manifests]# kubectl get pods -l "chenxi notin (cx,hgf)" NAME READY STATUS RESTARTS AGE myapp-84cd4b7f95-g6ldp 1/1 Running 3 9d
许多资源支持内嵌字段定义其使用的标签选择器
matchLabels:直接给定值
matchExpressions:基于给定的表达式来定义使用标签选择器{key:"KEY",operator:“表达式”,values:[VAL1,VAL2,...]}
表达式操作符:In ,NotIN:values字段的值必须为非空列表;Exists,NotExist:values字段的值必须为空列表
查看节点标签
[root@master manifests]# kubectl get nodes --show-labels NAME STATUS ROLES AGE VERSION LABELS master Ready master 9d v1.15.1 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/arch=amd64,kubernetes.io/hostname=master,kubernetes.io/os=linux,node-role.kubernetes.io/master= node01 Ready <none> 9d v1.15.1 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/arch=amd64,kubernetes.io/hostname=node01,kubernetes.io/os=linux node02 Ready <none> 9d v1.15.1 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/arch=amd64,kubernetes.io/hostname=node02,kubernetes.io/os=linux
给节点打标签
[root@master manifests]# kubectl label node node01 chenxi=cx node/node01 labeled [root@master manifests]# kubectl get nodes -l chenxi --show-labels NAME STATUS ROLES AGE VERSION LABELS node01 Ready <none> 9d v1.15.1 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,chenxi=cx,kubernetes.io/arch=amd64,kubernetes.io/hostname=node01,kubernetes.io/os=linux
修改节点标签
[root@master manifests]# kubectl label node node01 chenxi=gfd --overwrite node/node01 labeled [root@master manifests]# kubectl get nodes -l chenxi=gfd --show-labels NAME STATUS ROLES AGE VERSION LABELS node01 Ready <none> 9d v1.15.1 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,chenxi=gfd,kubernetes.io/arch=amd64,kubernetes.io/hostname=node01,kubernetes.io/os=linux
节点标签选择器,从而觉得pods只运行在那类节点上
nodeSelector <map[string]string> NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
在yaml使用节点标签选择器
[root@master manifests]# vim pod.demo.yaml apiVersion: v1 kind: Pod metadata: name: pod-demo labels: app: myapp tier: frontend spec: containers: - name: myapp image: ikubernetes/myapp:v1 ports: - containerPort: 80 - name: busyboxa image: busybox:latest imagePullPolicy: IfNotPresent command: - "/bin/sh" - "-c" - "sleep 36000" nodeSelector: chenxi: df 运行在有chenxi标签并且值等于gfd的节点上
查看pod运行的节点
[root@master manifests]# kubectl get pods pod-demo -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES pod-demo 2/2 Running 0 60m 10.244.1.21 node01 <none> <none>
在node02上添加节点标签
[root@master manifests]# kubectl label node node02 chenxi=df node/node02 labeled [root@master manifests]# kubectl get nodes -l chenxi=df --show-labels NAME STATUS ROLES AGE VERSION LABELS node02 Ready <none> 9d v1.15.1 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,chenxi=df,kubernetes.io/arch=amd64,kubernetes.io/hostname=node02,kubernetes.io/os=linux
删除pod的重新创建
[root@master manifests]# kubectl create -f pod.demo.yaml pod/pod-demo created [root@master manifests]# kubectl get pods pod-demo -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES pod-demo 2/2 Running 0 6s 10.244.2.13 node02 <none> <none> [root@master manifests]# kubectl get pods pod-demo -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES pod-demo 2/2 Running 0 7s 10.244.2.13 node02 <none> <none> [root@master manifests]#
只运行在指定的节点上给出节点的名字
nodeName <string> 给出节点的名字 NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements.
添加注解;在元数据信息里
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 [root@master manifests]# cat pod.demo.yaml apiVersion: v1 kind: Pod metadata: name: pod-demo labels: app: myapp tier: frontend annotations: chenxi.com: "chenxi.com admin" spec: containers: - name: myapp image: ikubernetes/myapp:v1 ports: - containerPort: 80 - name: busyboxa image: busybox:latest imagePullPolicy: IfNotPresent command: - "/bin/sh" - "-c" - "sleep 36000" nodeSelector: chenxi: df kubectl delete -f pod.demo.yaml [root@master manifests]# kubectl create -f pod.demo.yaml pod/pod-demo created
查看添加到pod里的注释信息
[root@master manifests]# kubectl describe pods pod-demo Name: pod-demo Namespace: default Priority: 0 Node: node02/192.168.183.13 Start Time: Sun, 04 Aug 2019 23:12:26 +0800 Labels: app=myapp tier=frontend Annotations: chenxi.com: chenxi.com admin 添加的注解 Status: Running IP: 10.244.2.14 Containers: myapp: Container ID: docker://1cee7ac4e20056b2ce5d3b93b3844477bf7ed0710f6d6da4131622537ed124f0 Image: ikubernetes/myapp:v1 Image ID: docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513 Port: 80/TCP Host Port: 0/TCP State: Running Started: Sun, 04 Aug 2019 23:12:27 +0800 Ready: True Restart Count: 0 Environment: <none> Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-2m2ts (ro) busyboxa: Container ID: docker://2c1d7d7b6696fdad1de7dfa9c320879023b481119180f00c327639ebd52c1f10 Image: busybox:latest Image ID: docker-pullable://busybox@sha256:9f1003c480699be56815db0f8146ad2e22efea85129b5b5983d0e0fb52d9ab70 Port: <none> Host Port: <none> Command: /bin/sh -c sleep 36000 State: Running Started: Sun, 04 Aug 2019 23:12:28 +0800 Ready: True Restart Count: 0 Environment: <none> Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-2m2ts (ro) Conditions: Type Status Initialized True Ready True ContainersReady True PodScheduled True Volumes: default-token-2m2ts: Type: Secret (a volume populated by a Secret) SecretName: default-token-2m2ts Optional: false QoS Class: BestEffort Node-Selectors: chenxi=df Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s node.kubernetes.io/unreachable:NoExecute for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 13m default-scheduler Successfully assigned default/pod-demo to node02 Normal Pulled 13m kubelet, node02 Container image "ikubernetes/myapp:v1" already present on machine Normal Created 13m kubelet, node02 Created container myapp Normal Started 13m kubelet, node02 Started container myapp Normal Pulled 13m kubelet, node02 Container image "busybox:latest" already present on machine Normal Created 13m kubelet, node02 Created container busyboxa Normal Started 13m kubelet, node02 Started container busyboxa
pod 的状态
Pending:状态意味着,pod的YAML文件已经提交个Kubernetes,API对象已经被保存在Etcd里。但是。这个Pod里有些容器因为某种原因而不能被顺利创建,比如,调度不成功
Running:这个状态下的Pod已经调度成功,跟具体的节点绑定。它包含的容器都已经创建成功,并且至少有一个正在运行中
Succeeded:这个状态意味着,Pod里的所有容器都正常运行完毕,并且已经退出,这种情况在运行一次性任务时最为常见
Failed: 这个状态下,Pod里至少有一个容器以不正常的状态(非0的返回码)退出,这个状态的出现,意味着你得想办法Debug这个容器应用,例如查看Pod的Events和日志
Unknown:这个异常意味着Pod的状态不能持续地被kubelet汇报给kube-apiserver,这很可能主从节点间的通信出现了问题
Pod生命周期中的重要行为
初始化容器
容器探测:liveness探测容器是否处于存活状态;readiness:探测容器里的服务是否可以正常提供服务
容器重启策略:
restartPolicy <string> Restart policy for all containers within the pod. One of Always, OnFailure, Never. Default to Always. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy Always:#表示一旦Pod中的容器挂了,就把它重启,默认 OnFailure:只有状态错误是重启 Never:表示从不重启