kubernetes最小调度单元pod详解(一):https://developer.aliyun.com/article/1495547
dnsConfig
Specifies the DNS parameters of a pod. Parameters specified here will be
merged to the generated DNS configuration based on DNSPolicy.
dnsPolicy
Set DNS policy for the pod. Defaults to “ClusterFirst”. Valid values are
‘ClusterFirstWithHostNet’, ‘ClusterFirst’, ‘Default’ or ‘None’. DNS
parameters given in DNSConfig will be merged with the policy selected with
DNSPolicy. To have DNS options set along with hostNetwork, you have to
specify DNS policy explicitly to ‘ClusterFirstWithHostNet’.
enableServiceLinks
EnableServiceLinks indicates whether information about services should be
injected into pod’s environment variables, matching the syntax of Docker
links. Optional: Defaults to true.
ephemeralContainers <[]Object>
List of ephemeral containers run in this pod. Ephemeral containers may be
run in an existing pod to perform user-initiated actions such as debugging.
This list cannot be specified when creating a pod, and it cannot be
modified by updating the pod spec. In order to add an ephemeral container
to an existing pod, use the pod’s ephemeralcontainers subresource. This
field is alpha-level and is only honored by servers that enable the
EphemeralContainers feature.
hostAliases <[]Object>
HostAliases is an optional list of hosts and IPs that will be injected into
the pod’s hosts file if specified. This is only valid for non-hostNetwork
pods.
hostIPC
Use the host’s ipc namespace. Optional: Default to false.
hostNetwork
Host networking requested for this pod. Use the host’s network namespace.
If this option is set, the ports that will be used must be specified.
Default to false.
hostPID
Use the host’s pid namespace. Optional: Default to false.
hostname
Specifies the hostname of the Pod If not specified, the pod’s hostname will
be set to a system-defined value.
imagePullSecrets <[]Object>
ImagePullSecrets is an optional list of references to secrets in the same
namespace to use for pulling any of the images used by this PodSpec. If
specified, these secrets will be passed to individual puller
implementations for them to use. For example, in the case of docker, only
DockerConfig type secrets are honored. More info:
https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod
initContainers <[]Object>
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/
nodeName
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.
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/
overhead <map[string]string>
Overhead represents the resource overhead associated with running a pod for
a given RuntimeClass. This field will be autopopulated at admission time by
the RuntimeClass admission controller. If the RuntimeClass admission
controller is enabled, overhead must not be set in Pod create requests. The
RuntimeClass admission controller will reject Pod create requests which
have the overhead already set. If RuntimeClass is configured and selected
in the PodSpec, Overhead will be set to the value defined in the
corresponding RuntimeClass, otherwise it will remain unset and treated as
zero. More info:
https://git.k8s.io/enhancements/keps/sig-node/20190226-pod-overhead.md This
field is alpha-level as of Kubernetes v1.16, and is only honored by servers
that enable the PodOverhead feature.
preemptionPolicy
PreemptionPolicy is the Policy for preempting pods with lower priority. One
of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.
This field is beta-level, gated by the NonPreemptingPriority feature-gate.
priority
The priority value. Various system components use this field to find the
priority of the pod. When Priority Admission Controller is enabled, it
prevents users from setting this field. The admission controller populates
this field from PriorityClassName. The higher the value, the higher the
priority.
priorityClassName
If specified, indicates the pod’s priority. “system-node-critical” and
“system-cluster-critical” are two special keywords which indicate the
highest priorities with the former being the highest priority. Any other
name must be defined by creating a PriorityClass object with that name. If
not specified, the pod priority will be default or zero if there is no
default.
readinessGates <[]Object>
If specified, all readiness gates will be evaluated for pod readiness. A
pod is ready when all its containers are ready AND all conditions specified
in the readiness gates have status equal to “True” More info:
https://git.k8s.io/enhancements/keps/sig-network/0007-pod-ready%2B%2B.md
restartPolicy
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
默认总是重启
runtimeClassName
RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group,
which should be used to run this pod. If no RuntimeClass resource matches
the named class, the pod will not be run. If unset or empty, the “legacy”
RuntimeClass will be used, which is an implicit class with an empty
definition that uses the default runtime handler. More info:
https://git.k8s.io/enhancements/keps/sig-node/runtime-class.md This is a
beta feature as of Kubernetes v1.14.
schedulerName
If specified, the pod will be dispatched by specified scheduler. If not
specified, the pod will be dispatched by default scheduler.
securityContext
SecurityContext holds pod-level security attributes and common container
settings. Optional: Defaults to empty. See type description for default
values of each field.
serviceAccount
DeprecatedServiceAccount is a depreciated alias for ServiceAccountName.
Deprecated: Use serviceAccountName instead.
serviceAccountName
ServiceAccountName is the name of the ServiceAccount to use to run this
pod. More info:
https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
setHostnameAsFQDN
If true the pod’s hostname will be configured as the pod’s FQDN, rather
than the leaf name (the default). In Linux containers, this means setting
the FQDN in the hostname field of the kernel (the nodename field of struct
utsname). In Windows containers, this means setting the registry value of
hostname for the registry key
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters to
FQDN. If a pod does not have FQDN, this has no effect. Default to false.
shareProcessNamespace
Share a single process namespace between all of the containers in a pod.
When this is set containers will be able to view and signal processes from
other containers in the same pod, and the first process in each container
will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both
be set. Optional: Default to false.
subdomain
If specified, the fully qualified Pod hostname will be
“...svc.”. If not
specified, the pod will not have a domainname at all.
terminationGracePeriodSeconds
Optional duration in seconds the pod needs to terminate gracefully. May be
decreased in delete request. Value must be non-negative integer. The value
zero indicates stop immediately via the kill signal (no opportunity to shut
down). If this value is nil, the default grace period will be used instead.
The grace period is the duration in seconds after the processes running in
the pod are sent a termination signal and the time when the processes are
forcibly halted with a kill signal. Set this value longer than the expected
cleanup time for your process. Defaults to 30 seconds.
tolerations <[]Object>
If specified, the pod’s tolerations.
topologySpreadConstraints <[]Object>
TopologySpreadConstraints describes how a group of pods ought to spread
across topology domains. Scheduler will schedule pods in a way which abides
by the constraints. All topologySpreadConstraints are ANDed.
volumes <[]Object>
List of volumes that can be mounted by containers belonging to the pod.
More info: https://kubernetes.io/docs/concepts/storage/volumes
#查看pod.spec.containers字段如何定义:
[root@master01 pod-test ]# kubectl explain pod.spec.containers
KIND: Pod
VERSION: v1
RESOURCE: containers <[]Object> containers下面接的是对象列表
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. #container是定义在pod里面的,一个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
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.
#image是用来指定容器需要的镜像的
imagePullPolicy
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
#镜像拉取策略,pod是要调度到node节点的,那pod启动需要镜像,可以根据这个字段设置镜像拉取策略,支持如下三种: Always:不管本地是否存在镜像,都要重新拉取镜像,默认值 Never: 从不拉取镜像 IfNotPresent:如果本地存在,使用本地的镜像,本地不存在,从官方拉取镜像
lifecycle
Actions that the management system should take in response to container
lifecycle events. Cannot be updated.
livenessProbe
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 -required- #name是必须字段,用来指定容器名字的
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> #port是端口,属于对象列表
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
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
Compute Resources required by this container. Cannot be updated. More info:
https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
securityContext
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
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. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
stdin
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
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
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
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
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.
volumeMounts <[]Object>
Pod volumes to mount into the container’s filesystem. Cannot be updated.
workingDir
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.spec.containers.ports字段如何定义:
[root@master01 pod-test ]# kubectl explain pod.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 -required- #containerPort是必须字段, pod中的容器需要暴露的端口。
Number of port to expose on the pod’s IP address. This must be a valid port
number, 0 < x < 65536.
hostIP #将容器中的服务暴露到宿主机的端口上时,可以指定绑定的宿主机 IP。
What host IP to bind the external port to.
hostPort #容器中的服务在宿主机上映射的端口
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
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
Protocol for port. Must be UDP, TCP, or SCTP. Defaults to “TCP”.
2、通过资源清单文件创建第一个Pod:
[root@master01 pod-test ]# cat podtest.yaml
apiVersion: v1
kind: Pod
metadata:
name: test
namespace: default
labels:
app: tomcat-test
spec:
containers:
- name: tomcat-12image: xianchao/tomcat-8.5-jre8:v1imagePullPolicy: IfNotPresentports:
- containerPort: 8080
没做node name 指定调度到相应节点。没写节点选择器,会随机的调度到一个node节点
#导入镜像
把xianchao-tomcat.tar.gz上传到node01和node02节点,手动导入镜像
[root@node02 ~ ]# docker load -i xianchao-tomcat.tar.gz df64d3292fd6: Loading layer [==================================================>] 4.672MB/4.672MB 0c3170905795: Loading layer [==================================================>] 3.584kB/3.584kB 9bca1faaa73e: Loading layer [==================================================>] 79.44MB/79.44MB e927085edc33: Loading layer [==================================================>] 2.56kB/2.56kB e5f8376fd9dc: Loading layer [==================================================>] 27.08MB/27.08MB e82a3681bb38: Loading layer [==================================================>] 2.048kB/2.048kB Loaded image: xianchao/tomcat-8.5-jre8:v1
#更新资源清单文件。apply是声明式更新,当yaml文件有更新,再次执行,pod也会随之更新。contianers里面的字段不让改
[root@master01 pod-test ]# kubectl apply -f podtest.yaml
pod/test created
查看pod是否创建成功
[root@master01 pod-test ]# kubectl get pod -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
test 1/1 Running 1 31m 172.21.231.131 node02
#查看pod日志
kubectl logs test
#查看pod里指定容器的日志
[root@master01 pod-test ]# kubectl logs test -c tomcat-12
#进入到刚才创建的pod,默认进入到pod里面的第一个容器
kubectl exec -it test – /bin/bash
[root@master01 pod-test ]# kubectl exec -it test – /bin/bash
bash-4.4# ping baidu.com
PING baidu.com (110.242.68.66): 56 data bytes
64 bytes from 110.242.68.66: seq=0 ttl=127 time=45.091 ms
64 bytes from 110.242.68.66: seq=1 ttl=127 time=46.269 ms
#假如pod里有多个容器,进入到pod里的指定容器,按如下命令
kubectl exec -it test -c tomcat-12 – /bin/bash
[root@master01 pod-test ]# kubectl exec -it test -c tomcat-12 – /bin/bash
bash-4.4# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
2: tunl0@NONE: mtu 1480 qdisc noop state DOWN qlen 1000
link/ipip 0.0.0.0 brd 0.0.0.0
4: eth0@if5: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1480 qdisc noqueue state UP
link/ether c2:b2:19:82:10:fe brd ff:ff:ff:ff:ff:ff
inet 172.21.231.131/32 scope global eth0
valid_lft forever preferred_lft forever
有时进入终端错误,那是因为镜像不支持,多换几个终端命令 – sh – /bin/sh – /bin/bash等
我们上面创建的pod是一个自主式pod,也就是通过pod创建一个应用程序,如果pod出现故障停掉,
那么我们通过pod部署的应用也就会停掉,不安全, 还有一种控制器管理的pod,通过控制器创建pod,
可以对pod的生命周期做管理,可以定义pod的副本数,如果有一个pod意外停掉,
那么会自动起来一个pod替代之前的pod,之后会讲解pod的控制器
Pod 阶段
Pod 的 status 字段是一个 PodStatus 对象,其中包含一个 phase 字段。
Pod 的阶段(Phase)是 Pod 在其生命周期中所处位置的简单宏观概述。
该阶段并不是对容器或 Pod 状态的综合汇总,也不是为了成为完整的状态机。
Pod 阶段的数量和含义是严格定义的。 除了本文档中列举的内容外,不应该再假定 Pod 有其他的 phase 值。
下面是 phase 可能的值:
取值 描述
Pending(悬决) Pod 已被 Kubernetes 系统接受,但有一个或者多个容器尚未创建亦未运行。
此阶段包括等待 Pod 被调度的时间和通过网络下载镜像的时间。
Running(运行中) Pod 已经绑定到了某个节点,Pod 中所有的容器都已被创建。至少有一个容器仍在运行,或者正处于启动或重启状态。
Succeeded(成功) Pod 中的所有容器都已成功终止,并且不会再重启。
Failed(失败) Pod 中的所有容器都已终止,并且至少有一个容器是因为失败终止。也就是说,容器以非 0 状态退出或者被系统终止。
Unknown(未知) 因为某些原因无法取得 Pod 的状态。这种情况通常是因为与 Pod 所在主机通信失败。
3、Pod常见状态
Unschedulable:Pod不能被调度,kube-scheduler没有匹配到合适的node节点。
PodScheduled:pod正处于调度中,在kube-scheduler刚开始调度的时候,还没有将pod分配到指定的node,在筛选出合适的节点后就会更新etcd数据,将pod分配到指定的node。
Failed:Pod中有容器启动失败而导致pod工作异常。
Unknown:由于某种原因无法获得pod的当前状态,通常是由于与pod所在的node节点通信错误。
Initialized:所有pod中的初始化容器已经完成了
ContainerCreating 正在创建
Running:Pod内部的容器已经被创建并且启动。
Ready:表示pod中的容器已经可以提供访问服务。
Completed:运行完成,容器中的进程运行完毕退出等导致的
Error: pod启动过程中发生错误
NodeLost:Pod所在节点失联
Waiting:Pod等待启动
Terminating:Pod正在被销毁
CrashLoopBackOff :pod创建失败,但是kubelet正在将它重启
ErrImagePull:镜像拉取出错,超时或下载被强制终止
ImagePullBackOff:Pod所在的node节点下载镜像失败
Pending:正在创建Pod但是Pod中的容器还没有全部被创建完成=处于此状态的Pod应该检查Pod依赖的存储是否有权限挂载等。
InvalidImageName:node节点无法解析镜像名称导致的镜像无法下载
ImageInspectError:无法校验镜像,镜像不完整导致
ErrImageNeverPull:策略禁止拉取镜像,镜像中心权限是私有等
RegistryUnavailable:镜像服务器不可用,网络原因或harbor宕机
CreateContainerConfigError:不能创建kubelet使用的容器配置
CreateContainerError:创建容器失败
RunContainerError:pod运行失败,容器中没有初始化PID为1的守护进程等
ContainersNotInitialized:pod没有初始化完毕
ContainersNotReady:pod没有准备完毕
ContainerCreating:pod正在创建中
PodInitializing:pod正在初始化中
DockerDaemonNotReady:node节点decker服务没有启动
NetworkPluginNotReady:网络插件没有启动
Evicted状态:出现这种情况,多见于系统内存或硬盘资源不足,
可df-h查看docker存储所在目录的资源使用情况,如果百分比大于85%,就要及时清理下资源,尤其是一些大文件、docker镜像。
CrashLoopBackOff:容器曾经启动了,但可能又异常退出了。这种情况需要看下容器的日志来排错 kubectl logs pod名称
Error 状态:Pod 启动过程中发生了错误, 这种情况需要看下容器的日志来排错 kubectl logs pod名称
4、通过kubectl run创建Pod 不常用。
可以通过kubectl run --help查看支持的命令:
[root@master01 ~ ]# kubectl run --help
run后面就是创建pod的名字,标签
kubectl run tomcat --image=xianchao/tomcat-8.5-jre8:v1 --image-pull-policy=‘IfNotPresent’ --port=8080
将pod导出为yaml文件:
[root@master01 pod-test ]# kubectl get pod test -o yaml
apiVersion: v1
kind: Pod
metadata:
annotations:
cni.projectcalico.org/containerID: c4535e343feb60a1b907f864632a866f8d46226e160512c9ec8bfab341993d18
cni.projectcalico.org/podIP: 172.21.231.133/32
cni.projectcalico.org/podIPs: 172.21.231.133/32
kubectl.kubernetes.io/last-applied-configuration: |
{“apiVersion”:“v1”,“kind”:“Pod”,“metadata”:{“annotations”:{},“labels”:{“app”:“tomcat-test”},“name”:“test”,“namespace”:“default”},“spec”:{“containers”:[{“image”:“xianchao/tomcat-8.5-jre8:v1”,“imagePullPolicy”:“IfNotPresent”,“name”:“tomcat-12”,“ports”:[{“containerPort”:8080}]}]}}
creationTimestamp: “2022-07-29T08:28:15Z”
labels:
app: tomcat-test
name: test
namespace: default
resourceVersion: “28616”
uid: 2cd96c74-b77c-4759-b09f-f92dcc2e7e44
spec:
containers:
image: xianchao/tomcat-8.5-jre8:v1
imagePullPolicy: IfNotPresent
name: tomcat-12
ports:
containerPort: 8080
protocol: TCP
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: kube-api-access-s5btr
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: node02
preemptionPolicy: PreemptLowerPriority
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: kube-api-access-s5btr
projected:
defaultMode: 420
sources:
serviceAccountToken:
expirationSeconds: 3607
path: token
configMap:
items:
key: ca.crt
path: ca.crt
name: kube-root-ca.crt
downwardAPI:
items:
fieldRef:
apiVersion: v1
fieldPath: metadata.namespace
path: namespace
status:
conditions:
lastProbeTime: null
lastTransitionTime: “2022-07-29T08:28:15Z”
status: “True”
type: Initialized
lastProbeTime: null
lastTransitionTime: “2022-07-29T08:28:16Z”
status: “True”
type: Ready
lastProbeTime: null
lastTransitionTime: “2022-07-29T08:28:16Z”
status: “True”
type: ContainersReady
lastProbeTime: null
lastTransitionTime: “2022-07-29T08:28:15Z”
status: “True”
type: PodScheduled
containerStatuses:
containerID: docker://343ac0733296aaa41ab5e2d62a1121141c4785cc0284979d689d298cee2f7372
image: xianchao/tomcat-8.5-jre8:v1
imageID: docker://sha256:4ac473a3dd922eecfc8e0dabd9f6c410871dfd913fea49bfed3fb99924839131
lastState: {}
name: tomcat-12
ready: true
restartCount: 0
started: true
state:
running:
startedAt: “2022-07-29T08:28:16Z”
hostIP: 10.10.0.224
phase: Running
podIP: 172.21.231.133
podIPs:
ip: 172.21.231.133
qosClass: BestEffort
startTime: “2022-07-29T08:28:15Z”
kubectl run 不适合复杂的pod,只适合一些比较简便的pod,一般不建议使用
容器异常终止时,打印日志:
[root@master01 ~ ]#kubectl explain pods.spec.containers
terminationMessagePath
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
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.
terminationMessagePath 表示容器的异常终止消息的路径,默认在 /dev/termination-log 下。
当容器退出时,可以通过容器的状态看到退出信息。
自定义异常信息文件
apiVersion: v1
kind: Pod
metadata:
name: busybox
spec:
containers:
- name: busybox
image: busybox:stable
command: [“/bin/sh”]
terminationMessagePath: /root/test.log
args: [“-c”, “sleep 10 && echo Sleep expired > /root/test.log”]
此外,用户可以设置容器的 terminationMessagePolicy 字段,以便进一步自定义。
此字段默认为 “File”,这意味着仅从终止消息文件中检索终止消息。
通过将 terminationMessagePolicy 设置为 “FallbackToLogsOnError”,
你就可以告诉 Kubernetes,在容器因错误退出时,如果终止消息文件为空,则使用容器日志输出的最后一块作为终止消息。
日志输出限制为 2048 字节或 80 行,以较小者为准。
综上,就是k8s pod的详细介绍