K8s 使用资源清单创建资源

以命令的方式创建资源,命令很多,且很容易忘记。K8s 支持以配置清单(文件)的方式来创建,使用中支持 json 格式和 yaml 格式的方式创建资源清单,但是 yaml 有更好的可读性,所以我们都使用 yaml 进行资源清单的配置,在执行 kubectl create … 的时候,会将提交的 yaml 转换成 json 格式的数据提交给 api server。相比于命令,配置清单更有逻辑和可读性,而且便于存储,下次可以直接使用。

创建资源方法

​ apiserver 仅接受 json 格式的资源定义;
​ yaml 格式提供的配置清单,apiserver 可自动将其转换为 json 格式,然后在提交

资源的组成

1
2
3
4
5
6
7
8
9
10
大部分资源的配置清单都有五个资源组成:
apiVersion:标识方法为 group/version 的方式,如果没有group,则表示核心组。查看目前有哪些组可以用命令,kubuctl api-version 查看
kind:资源类型
metadata:元数据
name 名称需要唯一
namespace 命名空间
labels 标签
annotations 元数据
spec:不同资源的 spec 值不同,用来表示资源的期待状态。
status:当前资源的当前状态。(k8s 运行的目的就是将当前状态无限向期待状态靠近的过程)

资源太多,记不住怎么配置,我们可以使用 kubectl explain + 资源名称进行查看
例如,查看 pods 怎么配置就可以使用 kubectl explain pods。查看 pods 中 spce 怎么定义就可以使用,kubectl explain pods.spec

控制资源的命令

yaml 配置格式

将当前 pods 的配置已 yaml 格式查看

1
kubectl get pods nginx-deploy-5c9b546997-nv2xp -o 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
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
apiVersion: v1 # apiVersion 格式为 group/version,group 如果没有,则代表核心组。查看系统目前的所有组可以使用 kubectl api-versions
kind: Pod # 资源类别(例如: Pod,ReplicaSet, Deployment, StatefulSet【资源为有状态时使用】, DaemonSet【资源以系统守护进程方式运行】, Job【任务】等)
metadata: # 元数据(主要包含几个字段,name,namespace,labels,annotations)
creationTimestamp: "2019-05-18T06:12:22Z"
generateName: nginx-deploy-5c9b546997-
labels:
pod-template-hash: 5c9b546997
run: nginx-deploy
name: nginx-deploy-5c9b546997-nv2xp # 同一 namespace 下的名称应该是唯一的。
namespace: default
ownerReferences:
- apiVersion: apps/v1
blockOwnerDeletion: true
controller: true
kind: ReplicaSet
name: nginx-deploy-5c9b546997
uid: e6370699-7933-11e9-938b-00163e00a5a9
resourceVersion: "1384"
selfLink: /api/v1/namespaces/default/pods/nginx-deploy-5c9b546997-nv2xp
uid: e63921c9-7933-11e9-938b-00163e00a5a9
spec: # 要创建的资源对象的规则,用来定义一个我们所期待的资源所拥有的特性,依靠控制器确保这些特性得以满足。(不同的资源类型,字段不同。可以使用 kubectl explain 查看,其中 required 表示这个字段是必须的)
containers:
- image: nginx
imagePullPolicy: Always
name: nginx-deploy
ports:
- containerPort: 80
protocol: TCP
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: default-token-8dmfd
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: izrj94q5l72imm6kxm11qxz
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: default-token-8dmfd
secret:
defaultMode: 420
secretName: default-token-8dmfd
status: # 显示当前资源的当前状态,只读(由集群维护,我们不能定义)
conditions:
- lastProbeTime: null
lastTransitionTime: "2019-05-18T06:12:22Z"
status: "True"
type: Initialized
- lastProbeTime: null
lastTransitionTime: "2019-05-18T06:12:30Z"
status: "True"
type: Ready
- lastProbeTime: null
lastTransitionTime: "2019-05-18T06:12:30Z"
status: "True"
type: ContainersReady
- lastProbeTime: null
lastTransitionTime: "2019-05-18T06:12:22Z"
status: "True"
type: PodScheduled
containerStatuses:
- containerID: docker://ed801af51ea71b2538175f7814e7c3651e2121c498c6c12e2b912b868177762d
image: docker.io/nginx:latest
imageID: docker-pullable://docker.io/nginx@sha256:23b4dcdf0d34d4a129755fc6f52e1c6e23bb34ea011b315d87e193033bcd1b68
lastState: {}
name: nginx-deploy
ready: true
restartCount: 0
state:
running:
startedAt: "2019-05-18T06:12:29Z"
hostIP: 172.20.245.188
phase: Running
podIP: 10.244.1.2
qosClass: BestEffort
startTime: "2019-05-18T06:12:22Z"

获取 API 的分组信息

1
kubectl api-versions
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
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
apps/v1beta1
apps/v1beta2
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

查看资源支持的字段

查看资源支持的字段类型, 可以使用 kubectl explain + 资源名称 进行查看

1
kubectl explain pods
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
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/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/api-conventions.md#types-kinds

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

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

创建资源

1
2
3
[root@iZrj94q5l72imm6kxm11qvZ ~]# mkdir rexyan 
[root@iZrj94q5l72imm6kxm11qvZ ~]# cd rexyan
[root@iZrj94q5l72imm6kxm11qvZ rexyan]# vim pod-demo.yaml

内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
apiVersion: v1
kind: Pod
metadata:
name: pod-demo
namespace: default
labels:
app: myapp
author: rexyan
spec:
containers:
- name: myapp
image: ikubernetes/myapp:v1
- name: busybox
image: busybox
command:
- "/bin/sh"
- "-c"
- "sleep 3600"

创建资源

上面的资源清单是没有配置控制器的,pod 资源删除后就不会重新启动了,原因是没有控制器进行管理。

1
kubectl create -f pod-demo.yaml

查看信息, 可以看到名称叫做 pod-demo 的 pod 中,两个容器都处于 ready 状态了。

1
2
3
4
[root@iZrj94q5l72imm6kxm11qvZ rexyan]# kubectl get pods 
NAME READY STATUS RESTARTS AGE
nginx-deploy-5c9b546997-nv2xp 1/1 Running 0 123m
pod-demo 2/2 Running 0 12s

删除资源

可以使用 kubectl delete pods + pod 名称进行 pod 的删除

1
kubectl delete pods pod-demo

或者可以使用 kubectl delete -f 资源文件 进行操作

1
kubectl delete -f pod-demo.yaml

查看日志

如果 pod 中只有一个容器,那么可以使用 kubectl logs + Pod名称命令查看日志

1
2
3
4
5
6
7
[root@iZrj94q5l72imm6kxm11qvZ rexyan]# kubectl get pods 
NAME READY STATUS RESTARTS AGE
nginx-deploy-5c9b546997-nv2xp 1/1 Running 0 130m
pod-demo 2/2 Running 0 6m39s
[root@iZrj94q5l72imm6kxm11qvZ rexyan]# kubectl logs nginx-deploy-5c9b546997-nv2xp
10.244.0.0 - - [18/May/2019:06:13:18 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
10.244.0.0 - - [18/May/2019:06:22:16 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

如果 pod 中不止一个容器,那么就还需要使用 kubectl logs + Pod名称 + 容器名称 命令查看日志

1
2
3
[root@iZrj94q5l72imm6kxm11qvZ rexyan]# kubectl logs pod-demo
Error from server (BadRequest): a container name must be specified for pod pod-demo, choose one of: [myapp busybox]
[root@iZrj94q5l72imm6kxm11qvZ rexyan]# kubectl logs pod-demo myapp

查看详细信息

可以使用 kubectl describe + 资源类型 + 资源名称 查看资源的详细信息

1
kubectl describe pods pod-demo
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
ame:               pod-demo
Namespace: default
Priority: 0
PriorityClassName: <none>
Node: izrj94q5l72imm6kxm11qwz/172.20.245.187
Start Time: Sat, 18 May 2019 16:15:43 +0800
Labels: app=myapp
author=rexyan
Annotations: <none>
Status: Running
IP: 10.244.2.2
Containers:
myapp:
Container ID: docker://e6ea6ad778a56370635c90df49708e2607ec44effee0bc5ad40184693090d64c
Image: ikubernetes/myapp:v1
Image ID: docker-pullable://docker.io/ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513
Port: <none>
Host Port: <none>
State: Running
Started: Sat, 18 May 2019 16:15:46 +0800
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-8dmfd (ro)
busybox:
Container ID: docker://d4739ba88b3f00290f7b7dc6ddbfc74062b1fb8906fea0612339135609f2443f
Image: busybox
Image ID: docker-pullable://docker.io/busybox@sha256:4b6ad3a68d34da29bf7c8ccb5d355ba8b4babcad1f99798204e7abb43e54ee3d
Port: <none>
Host Port: <none>
Command:
/bin/sh
-c
sleep 3600
State: Running
Started: Sat, 18 May 2019 16:15:48 +0800
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-8dmfd (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
default-token-8dmfd:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-8dmfd
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 9m44s default-scheduler Successfully assigned default/pod-demo to izrj94q5l72imm6kxm11qwz
Normal Pulling 9m43s kubelet, izrj94q5l72imm6kxm11qwz Pulling image "ikubernetes/myapp:v1"
Normal Pulled 9m41s kubelet, izrj94q5l72imm6kxm11qwz Successfully pulled image "ikubernetes/myapp:v1"
Normal Created 9m41s kubelet, izrj94q5l72imm6kxm11qwz Created container myapp
Normal Started 9m41s kubelet, izrj94q5l72imm6kxm11qwz Started container myapp
Normal Pulling 9m41s kubelet, izrj94q5l72imm6kxm11qwz Pulling image "busybox"
Normal Pulled 9m39s kubelet, izrj94q5l72imm6kxm11qwz Successfully pulled image "busybox"
Normal Created 9m39s kubelet, izrj94q5l72imm6kxm11qwz Created container busybox
Normal Started 9m39s kubelet, izrj94q5l72imm6kxm11qwz Started container busybox

进入 pod 中的容器

1
kubectl exec -it pod-demo -c myapp -- /bin/sh

上面命令表示进入名字为 pod-demo 的 pod,容器名称为 myapp 的容器中。

快速创建 deployment

快速创建示例或者简单的 deployment 文件

1
k create deployment nginx --image=nginx --dry-run -o yaml > deployment.yaml