0%

k8s学习日记day4

kubernetes的Pod详解

1 Pod的介绍

1.1 Pod的结构

  • 每个Pod中都包含一个或者多个容器,这些容器可以分为两类:

  • ① 用户程序所在的容器,数量可多可少。

  • ② Pause容器,这是每个Pod都会有的一个根容器,它的作用有两个:

    • 可以以它为依据,评估整个Pod的健康状况。
    • 可以在根容器上设置IP地址,其它容器都共享此IP(Pod的IP),以实现Pod内部的网络通信(这里是Pod内部的通讯,Pod之间的通讯采用虚拟二层网络技术来实现,我们当前环境使用的是Flannel)。

1.2 Pod定义

  • 下面是Pod的资源清单:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
apiVersion: v1     #必选,版本号,例如v1
kind: Pod   #必选,资源类型,例如 Pod
metadata:   #必选,元数据
name: string #必选,Pod名称
namespace: string #Pod所属的命名空间,默认为"default"
labels:    #自定义标签列表
- name: string  
spec: #必选,Pod中容器的详细定义
containers: #必选,Pod中容器列表
- name: string #必选,容器名称
image: string #必选,容器的镜像名称
imagePullPolicy: [ Always|Never|IfNotPresent ] #获取镜像的策略
command: [string] #容器的启动命令列表,如不指定,使用打包时使用的启动命令
args: [string] #容器的启动命令参数列表
workingDir: string #容器的工作目录
volumeMounts: #挂载到容器内部的存储卷配置
- name: string #引用pod定义的共享存储卷的名称,需用volumes[]部分定义的的卷名
mountPath: string #存储卷在容器内mount的绝对路径,应少于512字符
readOnly: boolean #是否为只读模式
ports: #需要暴露的端口库号列表
- name: string #端口的名称
containerPort: int #容器需要监听的端口号
hostPort: int #容器所在主机需要监听的端口号,默认与Container相同
protocol: string #端口协议,支持TCP和UDP,默认TCP
env: #容器运行前需设置的环境变量列表
- name: string #环境变量名称
value: string #环境变量的值
resources: #资源限制和请求的设置
limits: #资源限制的设置
cpu: string #Cpu的限制,单位为core数,将用于docker run --cpu-shares参数
memory: string #内存限制,单位可以为Mib/Gib,将用于docker run --memory参数
requests: #资源请求的设置
cpu: string #Cpu请求,容器启动的初始可用数量
memory: string #内存请求,容器启动的初始可用数量
lifecycle: #生命周期钩子
postStart: #容器启动后立即执行此钩子,如果执行失败,会根据重启策略进行重启
preStop: #容器终止前执行此钩子,无论结果如何,容器都会终止
livenessProbe: #对Pod内各容器健康检查的设置,当探测无响应几次后将自动重启该容器
exec:   #对Pod容器内检查方式设置为exec方式
command: [string] #exec方式需要制定的命令或脚本
httpGet: #对Pod内个容器健康检查方法设置为HttpGet,需要制定Path、port
path: string
port: number
host: string
scheme: string
HttpHeaders:
- name: string
value: string
tcpSocket: #对Pod内个容器健康检查方式设置为tcpSocket方式
port: number
initialDelaySeconds: 0 #容器启动完成后首次探测的时间,单位为秒
timeoutSeconds: 0    #对容器健康检查探测等待响应的超时时间,单位秒,默认1秒
periodSeconds: 0    #对容器监控检查的定期探测时间设置,单位秒,默认10秒一次
successThreshold: 0
failureThreshold: 0
securityContext:
privileged: false
restartPolicy: [Always | Never | OnFailure] #Pod的重启策略
nodeName: <string> #设置NodeName表示将该Pod调度到指定到名称的node节点上
nodeSelector: obeject #设置NodeSelector表示将该Pod调度到包含这个label的node上
imagePullSecrets: #Pull镜像时使用的secret名称,以key:secretkey格式指定
- name: string
hostNetwork: false #是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络
volumes: #在该pod上定义共享存储卷列表
- name: string #共享存储卷名称 (volumes类型有很多种)
emptyDir: {} #类型为emtyDir的存储卷,与Pod同生命周期的一个临时目录。为空值
hostPath: string #类型为hostPath的存储卷,表示挂载Pod所在宿主机的目录
path: string    #Pod所在宿主机的目录,将被用于同期中mount的目录
secret:    #类型为secret的存储卷,挂载集群与定义的secret对象到容器内部
scretname: string
items:
- key: string
path: string
configMap: #类型为configMap的存储卷,挂载预定义的configMap对象到容器内部
name: string
items:
- key: string
path: string
  • 语法:查看每种资源的可配置项
1
2
3
4
5
6
7
# 查看某种资源可以配置的一级配置

kubectl explain 资源类型

# 查看属性的子属性

kubectl explain 资源类型.属性
  • 示例:查看资源类型为pod的可配置项
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
[root@master ~]# kubectl explain pod
KIND: Pod
VERSION: v1

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

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

kind <string>
Kind is a string value representing the REST resource this object
represents. Servers may infer this from the endpoint the client submits
requests to. Cannot be updated. In CamelCase. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

metadata <Object>
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

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

status <Object>
Most recently observed status of the pod. This data may not be up to date.
Populated by the system. Read-only. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conv
  • 示例:查看资源类型为Pod的metadata的属性的可配置项
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
[root@master ~]# kubectl explain pod.metadata
KIND: Pod
VERSION: v1

RESOURCE: metadata <Object>

DESCRIPTION:
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

ObjectMeta is metadata that all persisted resources must have, which
includes all objects users must create.

FIELDS:
annotations <map[string]string>
Annotations is an unstructured key value map stored with a resource that
may be set by external tools to store and retrieve arbitrary metadata. They
are not queryable and should be preserved when modifying objects. More
info: http://kubernetes.io/docs/user-guide/annotations

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

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

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

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

finalizers <[]string>
Must be empty before the object is deleted from the registry. Each entry is
an identifier for the responsible component that will remove the entry from
the list. If the deletionTimestamp of the object is non-nil, entries in
this list can only be removed. Finalizers may be processed and removed in
any order. Order is NOT enforced because it introduces significant risk of
stuck finalizers. finalizers is a shared field, any actor with permission
can reorder it. If the finalizer list is processed in order, then this can
lead to a situation in which the component responsible for the first
finalizer in the list is waiting for a signal (field value, external
system, or other) produced by a component responsible for a finalizer later
in the list, resulting in a deadlock. Without enforced ordering finalizers
are free to order amongst themselves and are not vulnerable to ordering
changes in the list.

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

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

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

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

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

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

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

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

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

uid <string>
UID is the unique in time and space value for this object. It is typically
generated by the server on successful creation of a resource and is not
allowed to change on PUT operations. Populated by the system. Read-only.
More info: http://kubernetes.io/docs/user-guide/identifiers#uids
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
在kubernetes中基本所有资源的一级属性都是一样的,主要包含5个部分:

apiVersion <string>:版本,有kubernetes内部定义,版本号必须用kubectl api-versions查询。

kind <string>:类型,有kubernetes内部定义,类型必须用kubectl api-resources查询。

metadata <Object>:元数据,主要是资源标识和说明,常用的有name、namespace、labels等。

spec <Object>:描述,这是配置中最重要的一部分,里面是对各种资源配置的详细描述。

status <Object>:状态信息,里面的内容不需要定义,由kubernetes自动生成。

**在上面的属性中,spec是接下来研究的重点,继续看下它的常见子属性:**

containers <[]Object>:容器列表,用于定义容器的详细信息。

nodeName <String>:根据nodeName的值将Pod调度到指定的Node节点上。

nodeSelector <map[]> :根据NodeSelector中定义的信息选择该Pod调度到包含这些Label的Node上。

hostNetwork <boolean>:是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络。

volumes <[]Object> :存储卷,用于定义Pod上面挂载的存储信息。

restartPolicy <string>:重启策略,表示Pod在遇到故障的时候的处理策略。

2 Pod的配置

2.1 概述

  • 本小节主要来研究pod.spec.containers属性,这也是Pod配置中最为关键的一项配置。

  • 示例:查看pod.spec.containers的可选配置项

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@master ~]# kubectl explain pod.spec.containers
# 返回的重要属性
KIND:     Pod
VERSION:  v1
RESOURCE: containers <[]Object>   # 数组,代表可以有多个容器FIELDS:
name  <string>     # 容器名称
image <string>     # 容器需要的镜像地址
imagePullPolicy  <string> # 镜像拉取策略
command  <[]string> # 容器的启动命令列表,如不指定,使用打包时使用的启动命令
args   <[]string> # 容器的启动命令需要的参数列表
env   <[]Object> # 容器环境变量的配置
ports <[]Object> # 容器需要暴露的端口号列表
resources <Object> # 资源限制和资源请求的设置

2.2 基本配置

  • 创建pod-base.yaml文件,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@master ~]# cat pod-base.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-base
namespace: dev
labels:
user: xudaxian
spec:
containers:
- name: nginx # 容器名称
image: 192.168.20.119/library/nginx:latest # 容器需要的镜像地址
- name: busybox # 容器名称
image: 192.168.20.119/library/busybox:latest # 容器需要的镜像地址
[root@master ~]# kubectl apply -f pod-base.yaml
pod/pod-base created
  • 上面定义了一个比较简单的Pod的配置,里面有两个容器:

    • nginx:用的是1.17.1版本的nginx镜像创建(nginx是一个轻量级的web容器)。
    • busybox:用的是1.30版本的busybox镜像创建(busybox是一个小巧的linux命令集合)。
  • 查看Pod状况:

1
2
3
[root@master ~]# kubectl get pods -n dev
NAME READY STATUS RESTARTS AGE
pod-base 1/2 CrashLoopBackOff 3 62s

表示当前pod里有2个容器其中一个容器故障了 并且pod一直在重启试图恢复它

  • 通过describe查看内部的详情:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
[root@master ~]# kubectl describe pod pod-base -n dev
Name: pod-base
Namespace: dev
Priority: 0
Node: node1/192.168.20.115
Start Time: Mon, 23 May 2022 20:18:00 +0000
Labels: user=xudaxian
Annotations: Status: Running
IP: 10.244.1.27
IPs:
IP: 10.244.1.27
Containers:
nginx:
Container ID: docker://69a12ef22071c018ad434d1a0ce507a9c6a29e036f4d3aa1051fceef35945235
Image: 192.168.20.119/library/nginx:latest
Image ID: docker-pullable://192.168.20.119/library/nginx@sha256:416d511ffa63777489af47f250b70d1570e428b67666567085f2bece3571ad83
Port: <none>
Host Port: <none>
State: Running
Started: Mon, 23 May 2022 20:18:01 +0000
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-gr9wn (ro)
busybox:
Container ID: docker://d5844970e09d9eb8d924562468cec75d4cf69090ed9db0d769759ac858e31497
Image: 192.168.20.119/library/busybox:latest
Image ID: docker-pullable://192.168.20.119/library/busybox@sha256:2ca5e69e244d2da7368f7088ea3ad0653c3ce7aaccd0b8823d11b0d5de956002
Port: <none>
Host Port: <none>
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: Completed
Exit Code: 0
Started: Mon, 23 May 2022 20:19:37 +0000
Finished: Mon, 23 May 2022 20:19:37 +0000
Ready: False
Restart Count: 4
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-gr9wn (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
default-token-gr9wn:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-gr9wn
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message

---- ------ ---- ---- -------

Normal Scheduled <unknown> default-scheduler Successfully assigned dev/pod-base to node1
Normal Pulling 2m53s kubelet, node1 Pulling image "192.168.20.119/library/nginx:latest"
Normal Pulled 2m53s kubelet, node1 Successfully pulled image "192.168.20.119/library/nginx:latest"
Normal Created 2m53s kubelet, node1 Created container nginx
Normal Started 2m52s kubelet, node1 Started container nginx
Normal Pulling 2m7s (x4 over 2m52s) kubelet, node1 Pulling image "192.168.20.119/library/busybox:latest"
Normal Pulled 2m6s (x4 over 2m52s) kubelet, node1 Successfully pulled image "192.168.20.119/library/busybox:latest"
Normal Created 2m6s (x4 over 2m52s) kubelet, node1 Created container busybox
Normal Started 2m6s (x4 over 2m52s) kubelet, node1 Started container busybox
Warning BackOff 2m5s (x5 over 2m50s) kubelet, node1 Back-off restarting failed container

此时已经运行起来了一个基本的Pod,虽然它暂时有问题

2.3 镜像拉取策略

  • 创建pod-imagepullpolicy.yaml文件,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@master ~]# cat pod-imagepullpolicy.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-imagepullpolicy
namespace: dev
labels:
user: xudaxian
spec:
containers:
- name: nginx # 容器名称
image: 192.168.20.119/library/nginx:latest # 容器需要的镜像地址
imagePullPolicy: Always # 用于设置镜像的拉取策略
- name: busybox # 容器名称
image: 192.168.20.119/library/busybox:latest # 容器需要的镜像地址
[root@master ~]# kubectl apply -f pod-imagepullpolicy.yaml
pod/pod-imagepullpolicy created
  • imagePullPolicy:用于设置镜像拉取的策略,kubernetes支持配置三种拉取策略:

    • Always:总是从远程仓库拉取镜像(一直远程下载)。
    • IfNotPresent:本地有则使用本地镜像,本地没有则从远程仓库拉取镜像(本地有就用本地,本地没有就使用远程下载)。
    • Never:只使用本地镜像,从不去远程仓库拉取,本地没有就报错(一直使用本地,没有就报错)。

默认值说明:

  • 如果镜像tag为具体的版本号,默认策略是IfNotPresent。

  • 如果镜像tag为latest(最终版本),默认策略是Always。

  • 查看Pod详情:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
[root@master ~]# kubectl get pods -n dev
NAME READY STATUS RESTARTS AGE
pod-base 1/2 CrashLoopBackOff 6 9m50s
pod-imagepullpolicy 1/2 CrashLoopBackOff 3 79s
[root@master ~]# kubectl describe pod pod-imagepullpolicy -n dev
Name: pod-imagepullpolicy
Namespace: dev
Priority: 0
Node: node2/192.168.20.124
Start Time: Mon, 23 May 2022 20:26:32 +0000
Labels: user=xudaxian
Annotations: Status: Running
IP: 10.244.2.39
IPs:
IP: 10.244.2.39
Containers:
nginx:
Container ID: docker://9ec1e08eb621e7bd27b58ef48837ea81df6a5841530f410196638ae0ad19c685
Image: 192.168.20.119/library/nginx:latest
Image ID: docker-pullable://192.168.20.119/library/nginx@sha256:416d511ffa63777489af47f250b70d1570e428b67666567085f2bece3571ad83
Port: <none>
Host Port: <none>
State: Running
Started: Mon, 23 May 2022 20:26:34 +0000
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-gr9wn (ro)
busybox:
Container ID: docker://1df3c0eec902d8d7e0965b4025665c1f34d1d4652929782670108ee75e42197b
Image: 192.168.20.119/library/busybox:latest
Image ID: docker-pullable://192.168.20.119/library/busybox@sha256:2ca5e69e244d2da7368f7088ea3ad0653c3ce7aaccd0b8823d11b0d5de956002
Port: <none>
Host Port: <none>
State: Terminated
Reason: Completed
Exit Code: 0
Started: Mon, 23 May 2022 20:28:01 +0000
Finished: Mon, 23 May 2022 20:28:01 +0000
Last State: Terminated
Reason: Completed
Exit Code: 0
Started: Mon, 23 May 2022 20:27:17 +0000
Finished: Mon, 23 May 2022 20:27:17 +0000
Ready: False
Restart Count: 4
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-gr9wn (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
default-token-gr9wn:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-gr9wn
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message

---- ------ ---- ---- -------

Normal Scheduled <unknown> default-scheduler Successfully assigned dev/pod-imagepullpolicy to node2
Normal Pulling 93s kubelet, node2 Pulling image "192.168.20.119/library/nginx:latest"
Normal Pulled 93s kubelet, node2 Successfully pulled image "192.168.20.119/library/nginx:latest"
Normal Created 92s kubelet, node2 Created container nginx
Normal Started 92s kubelet, node2 Started container nginx
Normal Pulling 50s (x4 over 92s) kubelet, node2 Pulling image "192.168.20.119/library/busybox:latest"
Normal Pulled 49s (x4 over 91s) kubelet, node2 Successfully pulled image "192.168.20.119/library/busybox:latest"
Normal Created 49s (x4 over 91s) kubelet, node2 Created container busybox
Normal Started 49s (x4 over 91s) kubelet, node2 Started container busybox
Warning BackOff 48s (x5 over 89s) kubelet, node2 Back-off restarting failed container

2.4 启动命令

  • 在前面的案例中,一直有一个问题没有解决,就是busybox容器一直没有成功运行,那么到底是什么原因导致这个容器的故障的呢?

  • 原来busybox并不是一个程序,而是类似于一个工具类的集合,kubernetes集群启动管理后,它会自动关闭。解决方法就是让其一直在运行,这就用到了command的配置。

  • 创建pod-command.yaml文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@master ~]# cat pod-command.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-command
namespace: dev
labels:
user: xudaxian
spec:
containers:
- name: nginx # 容器名称
image: 192.168.20.119/library/nginx:latest # 容器需要的镜像地址
imagePullPolicy: IfNotPresent # 设置镜像拉取策略
- name: busybox # 容器名称
image: 192.168.20.119/library/busybox:latest # 容器需要的镜像地址
command: ["/bin/sh","-c","touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt;sleep 3;done;"]
[root@master ~]# kubectl apply -f pod-command.yaml
pod/pod-command unchanged
[root@master ~]# kubectl get pods -n dev
NAME READY STATUS RESTARTS AGE
pod-base 1/2 CrashLoopBackOff 7 16m
pod-command 2/2 Running 0 91s
pod-imagepullpolicy 1/2 CrashLoopBackOff 6 7m34s

command:用于在Pod中的容器初始化完毕之后执行一个命令。

这里稍微解释下command中的命令的意思:

  • “/bin/sh”,”-c”:使用sh执行命令。

  • touch /tmp/hello.txt:创建一个/tmp/hello.txt的文件。

  • while true;do /bin/echo $(date +%T) >> /tmp/hello.txt;sleep 3;done:每隔3秒,向文件写入当前时间

  • 进入Pod中的busybox容器,查看文件内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@master ~]# kubectl exec -it pod-command -n dev -c busybox /bin/sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl kubectl exec [POD] -- [COMMAND] instead.
/ # tail -f /tmp/hello.txt
20:36:09
20:36:12
20:36:15
20:36:18
20:36:21
20:36:24
20:36:27
20:36:30
20:36:33
20:36:36
20:36:39
20:36:42
20:36:45
20:36:48
20:36:51
20:36:54
20:36:57
20:37:00

特别说明:通过上面发现command已经可以完成启动命令和传递参数的功能,为什么还要提供一个args选项,用于传递参数?其实和Docker有点关系,kubernetes中的command和args两个参数其实是为了实现覆盖Dockerfile中的ENTRYPOINT的功能:

  • 如果command和args均没有写,那么用Dockerfile的配置。

  • 如果command写了,但是args没有写,那么Dockerfile默认的配置会被忽略,执行注入的command。

  • 如果command没有写,但是args写了,那么Dockerfile中配置的ENTRYPOINT命令会被执行,使用当前args的参数。

  • 如果command和args都写了,那么Dockerfile中的配置会被忽略,执行command并追加上args参数。

2.5 环境变量(不推荐)

  • 创建pod-evn.yaml文件,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@master ~]# cat pod-env.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-env
namespace: dev
labels:
user: xudaxian
spec:
containers:
- name: nginx # 容器名称
image: 192.168.20.119/library/nginx:latest # 容器需要的镜像地址
imagePullPolicy: IfNotPresent # 设置镜像拉取策略
- name: busybox # 容器名称
image: 192.168.20.119/library/busybox:latest # 容器需要的镜像地址
command: ["/bin/sh","-c","touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt;sleep 3;done;"]
env:
- name: "username"
value: "admin"
- name: "password"
value: "123456"
[root@master ~]# kubectl apply -f pod-env.yaml
pod/pod-env created
  • 进入容器,输出环境变量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[root@master ~]# cat pod-env.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-env
namespace: dev
labels:
user: xudaxian
spec:
containers:
- name: nginx # 容器名称
image: 192.168.20.119/library/nginx:latest # 容器需要的镜像地址
imagePullPolicy: IfNotPresent # 设置镜像拉取策略
- name: busybox # 容器名称
image: 192.168.20.119/library/busybox:latest # 容器需要的镜像地址
command: ["/bin/sh","-c","touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt;sleep 3;done;"]
env:
- name: "username"
value: "admin"
- name: "password"
value: "123456"
[root@master ~]# kubectl apply -f pod-env.yaml
pod/pod-env created
[root@master ~]# kubectl exec -it pod-env -n dev -c busybox /bin/sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl kubectl exec [POD] -- [COMMAND] instead.
/ # echo $username
admin
/ # echo $password
123456

2.6 端口设置

  • 查看ports支持的子选项:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
[root@master ~]# 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 <integer> -required-
Number of port to expose on the pod's IP address. This must be a valid port
number, 0 < x < 65536.

hostIP <string>
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>
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>
Protocol for port. Must be UDP, TCP, or SCTP. Defaults to "TCP".
1
2
3
4
5
6
7
8
9
KIND:     Pod
VERSION: v1
RESOURCE: ports <[]Object>
FIELDS:
name <string> # 端口名称,如果指定,必须保证name在pod中是唯一的
containerPort <integer> # 容器要监听的端口(0<x<65536)
hostPort <integer> # 容器要在主机上公开的端口,如果设置,主机上只能运行容器的一个副本(一般省略)
hostIP <string> # 要将外部端口绑定到的主机IP(一般省略)
protocol <string> # 端口协议。必须是UDP、TCP或SCTP。默认为“TCP”
  • 创建pod-ports.yaml文件,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[root@master ~]# cat pod-ports.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-ports
namespace: dev
labels:
user: xudaxian
spec:
containers:
- name: nginx # 容器名称
image: 192.168.20.119/library/nginx:latest # 容器需要的镜像地址
imagePullPolicy: IfNotPresent # 设置镜像拉取策略
ports:
- name: nginx-port # 端口名称,如果执行,必须保证name在Pod中是唯一的
containerPort: 80 # 容器要监听的端口 (0~65536)
protocol: TCP # 端口协议
[root@master ~]# kubectl apply -f pod-ports.yaml
pod/pod-ports created
[root@master ~]# kubectl get pod -n dev -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod-base 1/2 CrashLoopBackOff 11 36m 10.244.1.27 node1 <none> <none>
pod-command 2/2 Running 0 21m 10.244.2.40 node2 <none> <none>
pod-env 2/2 Running 0 7m33s 10.244.1.28 node1 <none> <none>
pod-imagepullpolicy 1/2 CrashLoopBackOff 10 27m 10.244.2.39 node2 <none> <none>
pod-ports 1/1 Running 0 40s 10.244.2.41 node2 <none> <none>

访问Pod中的容器中的程序使用的是PodIp:containerPort。

2.7 资源配额

  • 容器中的程序要运行,肯定会占用一定的资源,比如CPU和内存等,如果不对某个容器的资源做限制,那么它就可能吃掉大量的资源,导致其他的容器无法运行。针对这种情况,kubernetes提供了对内存和CPU的资源进行配额的机制,这种机制主要通过resources选项实现,它有两个子选项:

    • limits:用于限制运行的容器的最大占用资源,当容器占用资源超过limits时会被终止,并进行重启。
    • requests:用于设置容器需要的最小资源,如果环境资源不够,容器将无法启动。
  • 可以通过上面的两个选项设置资源的上下限。

  • 创建pod-resoures.yaml文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
[root@master ~]# cat pod-resources.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-resoures
namespace: dev
labels:
user: xudaxian
spec:
containers:
- name: nginx # 容器名称
image: 192.168.20.119/library/nginx:latest # 容器需要的镜像地址
imagePullPolicy: IfNotPresent # 设置镜像拉取策略
ports: # 端口设置
- name: nginx-port # 端口名称,如果执行,必须保证name在Pod中是唯一的
containerPort: 80 # 容器要监听的端口 (0~65536)
protocol: TCP # 端口协议
resources: # 资源配额
limits: # 限制资源的上限
cpu: "2" # CPU限制,单位是core数
memory: "10Gi" # 内存限制
requests: # 限制资源的下限
cpu: "1" # CPU限制,单位是core数
memory: "10Mi" # 内存限制
[root@master ~]# kubectl apply -f pod-resources.yaml
pod/pod-resoures created
[root@master ~]# kubectl get pods -n dev
NAME READY STATUS RESTARTS AGE
pod-base 1/2 NotReady 13 41m
pod-command 2/2 Running 0 27m
pod-env 2/2 Running 0 13m
pod-imagepullpolicy 1/2 CrashLoopBackOff 11 33m
pod-ports 1/1 Running 0 6m23s
pod-resoures 1/1 Running 0 92s

cpu:core数,可以为整数或小数。

memory:内存大小,可以使用Gi、Mi、G、M等形式。

此时pod运行正常

  • 编辑Pod,修改resources.requests.memory的值为10Gi:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
[root@master ~]# cat pod-resources.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-resoures
namespace: dev
labels:
user: xudaxian
spec:
containers:
- name: nginx # 容器名称
image: 192.168.20.119/library/nginx:latest # 容器需要的镜像地址
imagePullPolicy: IfNotPresent # 设置镜像拉取策略
ports: # 端口设置
- name: nginx-port # 端口名称,如果执行,必须保证name在Pod中是唯一的
containerPort: 80 # 容器要监听的端口 (0~65536)
protocol: TCP # 端口协议
resources: # 资源配额
limits: # 限制资源的上限
cpu: "2" # CPU限制,单位是core数
memory: "10Gi" # 内存限制
requests: # 限制资源的下限
cpu: "1" # CPU限制,单位是core数
memory: "10Gi" # 内存限制
[root@master ~]# kubectl delete pods pod-resoures -n dev
pod "pod-resoures" deleted
[root@master ~]# kubectl create -f pod-resources.yaml
pod/pod-resoures created
[root@master ~]# kubectl get pods -n dev
NAME READY STATUS RESTARTS AGE
pod-base 1/2 CrashLoopBackOff 14 47m
pod-command 2/2 Running 0 32m
pod-env 2/2 Running 0 18m
pod-imagepullpolicy 1/2 CrashLoopBackOff 12 38m
pod-ports 1/1 Running 0 11m
pod-resoures 0/1 Pending 0 7s
[root@master ~]# kubectl describe pods pod-resoures -n dev
Name: pod-resoures
Namespace: dev
Priority: 0
Node: <none>
Labels: user=xudaxian
Annotations: <none>
Status: Pending
IP:
IPs: <none>
Containers:
nginx:
Image: 192.168.20.119/library/nginx:latest
Port: 80/TCP
Host Port: 0/TCP
Limits:
cpu: 2
memory: 10Gi
Requests:
cpu: 1
memory: 10Gi
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-gr9wn (ro)
Conditions:
Type Status
PodScheduled False
Volumes:
default-token-gr9wn:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-gr9wn
Optional: false
QoS Class: Burstable
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message

---- ------ ---- ---- -------

Warning FailedScheduling <unknown> default-scheduler 0/3 nodes are available: 1 node(s) had taint {node-role.kubernetes.io/master: }, that the pod didn't tolerate, 2 Insufficient memory.
Warning FailedScheduling <unknown> default-scheduler 0/3 nodes are available: 1 node(s) had taint {node-role.kubernetes.io/master: }, that the pod didn't tolerate, 2 Insufficient memory.

提示 Insufficient memory 内存不足