K8S中所有的内容都抽象为资源,资源实例化之后叫做对象。一般使用yaml格式的文件来创建符合我们预期的pod,这样的yaml文件我们一般成为资源清单。
工作负载型资源(workload)
Pod、ReplicaSet、Deployment、StatefulSet、DaemonSet、Job、CronJob(ReplicationController在v1.11版本被废弃)
服务发现及负载均衡型资源(ServiceDiscovery LoadBalance)
Service、Ingress、……
配置与存储型资源
Volume(存储卷)、CSI(容器存储接口,可以扩展各种各样的第三方存储卷)
特殊类型的存储卷
ConfigMap(当配置中心来使用的资源类型)、Secret(保存敏感信息)、DownwardAPI(把外部环境中的信息输出给容器)
Namespace、Node、Role、ClusterRole、RoleBinding、ClusterRoleBinding
HPA、PodTemplate、LimitRange
yaml是一种可读性高,用来表达数据序列的格式。是一种标记语言,以数据为中心。
缩进时不允许使用Tab键,只允许使用空格
缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
【#】作为注释标识,从这个字符一直到行尾,都会被解释器忽略
对象:键值对的集合,又称为映射(Mapping)/哈希(hashes)/字典(dictionary)
数组:一组按次序排列的值,又称为序列(sequence)/列表(list)
纯量(scalars):单个的、不可再被拆分的值
对象的一组键值对使用冒号结构表示。
name: chinda
age: 20
yaml也允许另一种写法,将所有键值写成一个行内对象。
hash: { name: chinda, age: 20 }
一组连词线开头的行,构成一个数组。
animal:
数组也可以采用行内表示法。
animal: [Cat, Dog]
number: 12.30
isSet: true
parent: ~
date: 2020-04-23
e: !!str 123
f: !!str true
字符串默认不适用引号表示
str: 这是一行字符串
如果字符串之中包含空格或特殊字符,需要放在引号之间
str: '内容: 字符串'
单引号和双引号都可以使用,但是双引号不会对特殊字符进行转义
s1: '内容\n字符串'
s2: "内容\n字符串"
单引号之中如果还有单引号,必须连续使用两个单引号转义
str: 'this''s yaml'
参数名
字段类型
说明
apiVersion
String
K8S API的版本,目前基本上是v1,可以用kubectl api-versions命令查询
kind
String
yaml文件定义的资源类型和角色,例如:Pod,Deployment等
metadata
Object
元数据对象
metadata.name
String
元数据对象的名称,需自定义
metadata.namespace
String
元数据对象的命名空间,需自定义
spec
Object
详细定义对象
spec.containers[]
list
spec对象的容器列表
spec.containers[].name
String
容器名称
spec.containers[].image
String
容器镜像
spec.containers[].imagePullPolicy
String
容器镜像拉取策略,Always、Never、IfNotPresent三个值。1. 每次都尝试重新拉取镜像;2. Never:仅使用本地镜像;3. IfNotPresent:本地有镜像就使用本地镜像,没有就拉取在线镜像。默认值:Always
spec.containers[].command[]
list
容器启动命令,可以指定多个,不指定则使用镜像Dockerfile编写时使用的启动命令
spec.containers[].args[]
list
启动命令参数,可以指定多个
spec.containers[].workingDir
String
容器的工作目录
spec.containers[].volumeMounts[]
list
容器内部的存储卷配置
spec.containers[].volumeMounts[].name
String
可以被容器挂载的存储卷名称
spec.containers[].volumeMounts[].mountPath
String
可以被容器挂在的存储卷路径
spec.containers[].volumeMounts[].readOnly
boolean
设置存储卷路径的读写模式,默认为false
spec.containers[].ports[]
list
容器需要用到的端口列表
spec.containers[].ports[].name
String
端口名称
spec.containers[].ports[].containerPort
int
容器需要监听的端口号
spec.containers[].ports[].hostPort
int
容器所在主机需要监听的端口号,默认和containerPort相同。注意:设置hostPort主机无法启动该容器的相同副本(因为主机的端口不允许相同,端口会冲突)
spec.containers[].ports[].protocol
String
端口协议,支持TCP和UDP,默认为TCP
spec.containers[].env[]
list
容器运行的环境变量列表
spec.containers[].env[].name
String
环境变量名称
spec.containers[].env[].value
String
环境变量值
spec.containers[].resources
Object
资源限制和资源请求的值
spec.containers[].resources.limits
Object
设置容器运行时资源运行上限
spec.containers[].resources.limits.cpu
int
CPU的限制,单位为core数,将用于docker run --cpu-shares参数
spec.containers[].resources.limits.memory
String
指定MEM内存限制,单位为MiB、GiB
spec.containers[].resources.requests
Object
容器启动和调度时的限制设置
spec.containers[].resources.requests.cpu
int
CPU请求,单位为core数,容器启动时初始化可用数量
spec.containers[].resources.requests.memory
String
内存请求,单位为MiB、GiB,容器启动的初始化可用大小
spec.restartPolicy
String
定义Pod的重启策略,Always、OnFailure、Never,默认为Always。1. Always:Pod一旦终止运行,则无论容器时如何终止的,kubelet服务都将该Pod重启;2. OnFailure:只有Pod以非零推出终止时,kubelet才会重启该容器。如果容器正常结束(退出码为0),则kubelet将不会重启该Pod;3. Never:Pod终止后,kubelet将退出码报告给Master,不会重启该Pod
spec.nodeSelector
String
定义Node的Lable过滤标签
spec.imagePullSecrets[]
list
定义pull镜像时使用的secret名称,以name:secretkey格式指定
spec.hostNetwork
String
定义是否使用主机网络模式,默认值为false。设置true表示使用宿主机网络,不适用docker网桥,同时设置true将无法在同一台宿主机上启动第二个副本。
[root@k8s-master01 ~]# kubectl api-versions
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
[root@k8s-master01 ~]# 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/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
进一步查询
[root@k8s-master01 ~]# kubectl explain pod.apiVersion
KIND: Pod
VERSION: v1
FIELD: apiVersion <string>
DESCRIPTION:
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
Pod能够具有多个容器,应用运行在容器里面,但是它也可能有一个或多个先于应用容器启动的Init容器。
Init容器与普通容器区别:
如果Pod的Init容器失败,Kubenetes会不断地重启该Pod,直到Init容器成功为止。然而,如果Pod对应的restartPolicy为Never,它不会重新启动。
Init容器的优势:
apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app: myapp-pod
spec:
containers:
- name: myapp-pod
image: busybox
command: ['sh', '-c', 'echo The app is running! && sleep 3600']
initContainers:
- name: init-myservice
image: busybox
command: ['sh', '-c', 'until nslookup myservice; do echo waiting for myservice; sleep 2; done;']
- name: init-mydb
image: busybox
command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep2; done;']
[root@k8s-master01 ~]# kubectl create -f init-pod.yaml
pod/myapp-pod created
[root@k8s-master01 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
myapp-pod 0/1 Init:0/2 0 6s
# 查看Pod创建情况
[root@k8s-master01 ~]# kubectl describe pod
Name: myapp-pod
Namespace: default
Priority: 0
Node: k8s-node01/192.168.0.151
Start Time: Fri, 24 Apr 2020 07:12:09 +0800
Labels: app=myapp-pod
Annotations: <none>
Status: Pending
IP: 10.244.1.20
Init Containers:
init-myservice:
Container ID: docker://3d25dad40d7ee407e971ba33dd6e4b0acc1102b43a69d2906cb5f1a6c3bb1038
Image: busybox
Image ID: docker-pullable://busybox@sha256:a8cf7ff6367c2afa2a90acd081b484cbded349a7076e7bdf37a05279f276bc12
Port: <none>
Host Port: <none>
Command:
sh
-c
until nslookup myservice; do echo waiting for myservice; sleep 2; done;
State: Running
Started: Fri, 24 Apr 2020 07:12:13 +0800
Ready: False
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-wt4p2 (ro)
init-mydb:
Container ID:
Image: busybox
Image ID:
Port: <none>
Host Port: <none>
Command:
sh
-c
until nslookup mydb; do echo waiting for mydb; sleep2; done;
State: Waiting
Reason: PodInitializing
Ready: False
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-wt4p2 (ro)
Containers:
myapp-pod:
Container ID:
Image: busybox
Image ID:
Port: <none>
Host Port: <none>
Command:
sh
-c
echo The app is running! && sleep 3600
State: Waiting
Reason: PodInitializing
Ready: False
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-wt4p2 (ro)
Conditions:
Type Status
Initialized False
Ready False
ContainersReady False
PodScheduled True
Volumes:
default-token-wt4p2:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-wt4p2
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 78s default-scheduler Successfully assigned default/myapp-pod to k8s-node01
Normal Pulling 78s kubelet, k8s-node01 Pulling image "busybox"
Normal Pulled 75s kubelet, k8s-node01 Successfully pulled image "busybox"
Normal Created 75s kubelet, k8s-node01 Created container init-myservice
Normal Started 74s kubelet, k8s-node01 Started container init-myservice
# 查看容器日志
[root@k8s-master01 ~]# kubectl log myapp-pod -c init-myservice --tail=20
log is DEPRECATED and will be removed in a future version. Use logs instead.
Server: 10.96.0.10
Address: 10.96.0.10:53
** server can't find myservice.default.svc.cluster.local: NXDOMAIN
*** Can't find myservice.svc.cluster.local: No answer
*** Can't find myservice.cluster.local: No answer
*** Can't find myservice.default.svc.cluster.local: No answer
*** Can't find myservice.svc.cluster.local: No answer
*** Can't find myservice.cluster.local: No answer
原因:server can't find myservice.default.svc.cluster.local
apiVersion: v1
kind: Service
metadata:
name: myservice
spec:
selector:
app: myservice
ports:
- protocol: TCP
port: 80
targetPort: 9376
[root@k8s-master01 ~]# kubectl create -f myservice.yaml
[root@k8s-master01 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
myapp-pod 0/1 Init:1/2 0 18m
[root@k8s-master01 ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 6d10h
myservice ClusterIP 10.105.2.111 <none> 80/TCP 8m1s
[root@k8s-master01 ~]# kubectl create -f mydb.yaml
service/mydb created
[root@k8s-master01 ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 6d10h
mydb ClusterIP 10.96.64.206 <none> 80/TCP 46s
myservice ClusterIP 10.105.2.111 <none> 80/TCP 11m
[root@k8s-master01 ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
myapp-pod 1/1 Running 0 28m
探针是由kubelet对容器执行的定期诊断。要执行诊断,kubelet调用由容器实现的Handler。有三种类型的处理程序:
每次探测都将获得一下三种结果之一:
livenessProbe:指示容器是否正在运行。如果存活探测失败,则kubelet会杀死容器,并且容器将受到其重启策略的影响。如果容器不提供存活探针,则默认状态为Success。
readinessProbe:指示容器是否准备好服务请求。如果就绪探测失败,端点控制器将从与Pod相匹配的所有Service的端点中删除该Pod的IP地址。初始化延迟之前的就绪状态默认为Failure。如果容器不提供就绪探针,则默认状态为Success。
apiVersion: v1
kind: Pod
metadata:
name: readiness-http-get
labels:
app: readiness-http-get
spec:
containers:
- name: readiness-http-get
image: chinda.com/library/myapp:v1
imagePullPolicy: IfNotPresent
readinessProbe:
httpGet:
port: 80
path: /index1.html
initialDelaySeconds: 1
periodSeconds: 3
restartPolicy: Always
注意: myapp:v1 可以拉取wangyanglinux/myapp:v1
[root@k8s-master01 ~]# kubectl create -f readiness.yaml
pod/readiness-http-get created
[root@k8s-master01 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
readiness-http-get 0/1 Running 0 4m48s
[root@k8s-master01 ~]# kubectl describe pod readiness-http-get
Name: readiness-http-get
Namespace: default
Priority: 0
Node: k8s-node02/192.168.0.152
Start Time: Sat, 25 Apr 2020 09:23:29 +0800
Labels: app=readiness-http-get
Annotations: <none>
Status: Running
IP: 10.244.2.16
Containers:
readiness-http-get:
Container ID: docker://bb279fd59dcac6bf733c83c0e80d7b5acffb36f20beeae24c8adb9cf74e83ece
Image: chinda.com/library/myapp:v1
Image ID: docker-pullable://chinda.com/library/myapp@sha256:9eeca44ba2d410e54fccc54cbe9c021802aa8b9836a0bcf3d3229354e4c8870e
Port: <none>
Host Port: <none>
State: Running
Started: Sat, 25 Apr 2020 09:23:32 +0800
Ready: False
Restart Count: 0
Readiness: http-get http://:80/index1.html delay=1s timeout=1s period=3s #success=1 #failure=3
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-wt4p2 (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
default-token-wt4p2:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-wt4p2
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 7m5s default-scheduler Successfully assigned default/readiness-http-get to k8s-node02
Normal Pulling 7m4s kubelet, k8s-node02 Pulling image "chinda.com/library/myapp:v1"
Normal Pulled 7m2s kubelet, k8s-node02 Successfully pulled image "chinda.com/library/myapp:v1"
Normal Created 7m2s kubelet, k8s-node02 Created container readiness-http-get
Normal Started 7m2s kubelet, k8s-node02 Started container readiness-http-get
# 注意这句描述, 准备探针失败,状态码404
Warning Unhealthy 2m2s (x100 over 6m59s) kubelet, k8s-node02 Readiness probe failed: HTTP probe failed with statuscode: 404
原因是准备探测找到不index1.html页面
解决方案
# kubectl exec pod名称 -c 容器名称 -it -- /bin/sh 若pod中只有一个容器,可以省略-c
[root@k8s-master01 ~]# kubectl exec readiness-http-get -c readiness-http-get -it -- /bin/sh
/usr/share/nginx/html # cd /usr/share/nginx/html
/usr/share/nginx/html # ls
50x.html index.html
/usr/share/nginx/html # echo "123" >> index1.html
/usr/share/nginx/html # exit
[root@k8s-master01 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
readiness-http-get 1/1 Running 0 28m
apiVersion: v1
kind: Pod
metadata:
name: liveness-exec
labels:
app: liveness-exec
spec:
containers:
- name: liveness-exec
image: busybox
imagePullPolicy: IfNotPresent
command: ['/bin/sh', '-c', 'touch /tmp/live ; sleep 60; rm -rf /tmp/live; sleep 3600']
livenessProbe:
exec:
command:
- test
- -e
- tmp/live
initialDelaySeconds: 1
periodSeconds: 3
restartPolicy: Always
[root@k8s-master01 ~]# kubectl create -f liveness.yaml
pod/liveness-exec created
[root@k8s-master01 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
liveness-exec 1/1 Running 0 46s
# 若干时间后, pod已经重启2次
[root@k8s-master01 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
liveness-exec 1/1 Running 2 3m36s
Pod hook是由Kubernetes管理的kubelet发起的,当容器中的进程启动前或者容器中的进程终止之前运行,这是包含在容器的生命周期之中。可以同时为Pod中的所有容器都配置hook。
Hook的类型包括两种:
apiVersion: v1
kind: Pod
metadata:
name: hook-pod
labels:
app: hook-pod
spec:
containers:
- name: hook-pod
image: nginx
imagePullPolicy: IfNotPresent
lifecycle:
postStart:
exec:
command:
- /bin/sh
- -c
- echo hello from the postStart handler > /usr/share/message
preStop:
exec:
command:
- /bin/sh
- -c
- echo hello from the postStop handler > /usr/share/message
restartPolicy: Always
[root@k8s-master01 ~]# kubectl create -f hook.yaml
pod/hook-pod created
[root@k8s-master01 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
hook-pod 0/1 ContainerCreating 0 8s
[root@k8s-master01 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
hook-pod 1/1 Running 0 101s
[root@k8s-master01 ~]# kubectl exec hook-pod -it -- /bin/sh
# cat /usr/share
cat: /usr/share: Is a directory
# cat /usr/share/message
hello from the postStart handler
PodSpec中restartPolicy字段,值为Always、OnFailure、Never,默认为Always。restartPolicy适用于所有容器,仅指通过同一节点上的kubelet重新启动容器。失败的容器由kubelet以5分钟为上限的指数退避延迟(10s、20s、40s……)重启,并在成功执行十分钟后重置。
Pod的status字段是一个PodStatus对象,PodStatus中由一个phase字段。相位(phase)是Pod在其生命周期中的简单宏观概述。该阶段并不是对容器或Pod的综合汇总,也不是为了作为综合状态机。
phase的值:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章