K8s核心资源对象-Pod(Container)

基于1.25

Container相关字段

// Container represents a single container that is expected to be run on the host.
type Container struct {
// Required: This must be a DNS_LABEL. Each container in a pod must
// have a unique name.
Name string
// Required.
Image string
// Optional: The container image's entrypoint is used if this is not provided; cannot be updated.
// 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. Double $$ are reduced
// to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. "$$(VAR_NAME)" will
// produce the string literal "$(VAR_NAME)". Escaped references will never be expanded, regardless
// of whether the variable exists or not.
// +optional
Command []string
// Optional: The container image's cmd is used if this is not provided; cannot be updated.
// 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. Double $$ are reduced
// to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. "$$(VAR_NAME)" will
// produce the string literal "$(VAR_NAME)". Escaped references will never be expanded, regardless
// of whether the variable exists or not.
// +optional
Args []string
// Optional: Defaults to the container runtime's default working directory.
// +optional
WorkingDir string
// +optional
Ports []ContainerPort
// 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.
// +optional
EnvFrom []EnvFromSource
// +optional
Env []EnvVar
// Compute resource requirements.
// +optional
Resources ResourceRequirements
// +optional
VolumeMounts []VolumeMount
// volumeDevices is the list of block devices to be used by the container.
// +optional
VolumeDevices []VolumeDevice
// +optional
LivenessProbe *Probe
// +optional
ReadinessProbe *Probe
// +optional
StartupProbe *Probe
// +optional
Lifecycle *Lifecycle
// Required.
// +optional
TerminationMessagePath string
// +optional
TerminationMessagePolicy TerminationMessagePolicy
// Required: Policy for pulling images for this container
ImagePullPolicy PullPolicy
// Optional: SecurityContext defines the security options the container should be run with.
// If set, the fields of SecurityContext override the equivalent fields of PodSecurityContext.
// +optional
SecurityContext *SecurityContext

// Variables for interactive containers, these have very specialized use-cases (e.g. debugging)
// and shouldn't be used for general purpose containers.
// +optional
Stdin bool
// +optional
StdinOnce bool
// +optional
TTY bool
}

主要分为:

  • 镜像相关:Image、ImagePullPolicy
  • 程序执行入口相关:Command、Args、WorkingDir
  • 容器暴露端口:Ports
  • 环境变量:Env、EnvFrom
  • 卷相关:VolumeMounts、VolumeDevices
  • 资源相关字段:Resource
  • 容器生命周期相关:LifeCycle、TerminationMessagePath、TerminationMessagePolicy、LivenessProbe、ReadinessProbe、StartupProbe
  • 安全上下文相关:SecurityContext
  • 调试相关:Stdin、StdinOnce

镜像相关

Image

镜像的名称

ImagePullPolicy

镜像拉取策略:

// shouldPullImage returns whether we should pull an image according to
// the presence and pull policy of the image.
func shouldPullImage(container *v1.Container, imagePresent bool) bool {
if container.ImagePullPolicy == v1.PullNever {
return false
}

if container.ImagePullPolicy == v1.PullAlways ||
(container.ImagePullPolicy == v1.PullIfNotPresent && (!imagePresent)) {
return true
}

return false
}

容器进入执行入口相关

// ExpandContainerCommandAndArgs expands the given Container's command by replacing variable references `with the values of given EnvVar.
func ExpandContainerCommandAndArgs(container *v1.Container, envs []EnvVar) (command []string, args []string) {
mapping := expansion.MappingFuncFor(envVarsToMap(envs))

if len(container.Command) != 0 {
for _, cmd := range container.Command {
command = append(command, expansion.Expand(cmd, mapping))
}
}

if len(container.Args) != 0 {
for _, arg := range container.Args {
args = append(args, expansion.Expand(arg, mapping))
}
}

return command, args
}

Command

容器进程执行入口点数组,不再Shell中执行

  • 如果未提供,使用容器镜像的ENTRYPOINT

Args

容器镜像的ENTRYPOINT参数

  • 未提供,使用容器镜像CMD设置

WorkingDir

容器的工作目录

  • 如果未指定,则使用容器运行时的默认值,默认值在容器镜像中的配置

容器暴露的端口

Ports是对外暴力的端口列表,有以下字段


// MakePortMappings creates internal port mapping from api port mapping.
func MakePortMappings(container *v1.Container) (ports []PortMapping) {
names := make(map[string]struct{})
for _, p := range container.Ports {
pm := PortMapping{
HostPort: int(p.HostPort),
ContainerPort: int(p.ContainerPort),
Protocol: p.Protocol,
HostIP: p.HostIP,
}

// We need to determine the address family this entry applies to. We do this to ensure
// duplicate containerPort / protocol rules work across different address families.
// https://github.com/kubernetes/kubernetes/issues/82373
family := "any"
if p.HostIP != "" {
if utilsnet.IsIPv6String(p.HostIP) {
family = "v6"
} else {
family = "v4"
}
}

var name = p.Name
if name == "" {
name = fmt.Sprintf("%s-%s-%s:%d:%d", family, p.Protocol, p.HostIP, p.ContainerPort, p.HostPort)
}

// Protect against a port name being used more than once in a container.
if _, ok := names[name]; ok {
klog.InfoS("Port name conflicted, it is defined more than once", "portName", name)
continue
}
ports = append(ports, pm)
names[name] = struct{}{}
}
return
}

环境变量Env、EnvFrom

在容器设置的环境变量列表,支持字符串、ConfigMap、Secret、metadata、spec.resource等多种方式

卷相关

VolumeMounts

挂载到容器文件系统中Pod卷

VolumeDevices

容器要使用的块设备列表,描述了容器内原始块的设备映射

资源相关

Resource主要是requests和limits

  • requests:最小的资源用量
    • 如果只设置了limits,默认是取limits一样的值
  • limits:与允许使用最大资源用量,设置为cgroup的值

容器生命周期相关

Lifecycle

描述管理系统为响应容器生命周期事件采取的行动,对于postStart和preStop生命周期处理程序,容器管理会被阻塞,直到操作完成。

  • postStart:创建容器成功之后马上调用postStart,处理程序启动失败,按照重启策略重启。过程中其他操作被阻塞
  • preStop:preStop在容器因为API请求或管理事件(如存活探针/启动探针失败、抢占、资源竞用等)终止前调用。容器崩溃退出不调用

TerminationMessagePath

如何填充终止消息。字段File使用TerminationMessagePath填充容器失败的消息。FallbackToLogOnError则输出到容器最后。

  • 日志输出限制2058字节或者80行,默认为File

LivenessProbe

容器存活探针,定期执行。如果探针失败,则容器重启

ReadinessProbe

容器服务就绪探针,定期执行。如果探针失败,从服务端点删除

StartupProbe

容器启动探针,StartupProbe表示这个Pod已经初始化。设置了此字段,会优先其他探针,如果失败,容器重启

  • 一般用于记载预习数据

安全上下文

SecurityContext定义了容器的运行的安全选项

  • 如果设置会覆盖PodSecurityContext

调试相关

Stdin

容器在运行时是否为sydin分配缓冲区

  • 未设置,从容器的stdio读取数据始终未EOF,默认false

StdinOnce

容器运行某个attch之后,打开stdio通道之后是否关闭它。