一、kubernetes是有一个restful风格的 API,把各种操作对象都一律当做资源来管理。并且可通过标准的HTTP请求的方法 GET,PUT,DELETE,POST,等方法来完成操作,不过是通过相应的命令反馈在kubectl 之上,如kubectl run,get,edit,...。
二、k8s常用的资源实例化后我们称之为对象。k8s相关的核心资源如下。
1、workload(工作负载型资源对象):Pod,ReplicaSet,Deployment,StatefulSet,DaemonSet,Job,Cronjob...
2、Service,Ingress 服务发现和负载均衡有关 ....
3、Volume 配置与存储。 现在的k8s版本还支持基于CSI,容器存储接口来支持各种各样的存储卷。我们还有另外两种特殊类型的存储卷。
a、ConfigMap :用来当配置中心使用的资源
b、Secret:和ConfigMap 功能相同但是用来保存敏感数据。
c、DownwardAPI:把外部环境中的信息输出给容器
4、集群级的资源
a、Namespace,Node,Role(名称空间级的资源),ClusterRole,RoleBinding,ClusterRoleBinding
5、元数据型资源
a、HPA
b、PodTemplate用于pod控制器创建pod时使用的模板。
c、LimitRange 定义资源限制
6、包括但不仅限于上述资源
三、yaml详解
1、将pod信息以yaml格式输出
[root@k8smaster ~]# kubectl get pods NAME READY STATUS RESTARTS AGE myapp-848b5b879b-5k4s4 1/1 Running 0 22h myapp-848b5b879b-bzblz 1/1 Running 0 22h myapp-848b5b879b-hzbf5 1/1 Running 0 22h nginx-deploy-5b595999-d9lv5 1/1 Running 0 1d [root@k8smaster ~]# kubectl get pod myapp-848b5b879b-5k4s4 -o yaml #以yaml格式输出 apiVersion: v1 #定义对象属于k8s哪一个对应的api群组的名称和版本,给定api版本时由两个部分组成,group/version,group如果省略,表示core定义(核心组,最根本的资源) kind: Pod #定义资源类别。用来指明这是每一种资源用来实例化成一个具体的资源对象时使用。 metadata: #元数据,内部嵌套很多二级字段和三级字段来定义 creationTimestamp: 2019-05-09T09:10:00Z generateName: myapp-848b5b879b- labels: pod-template-hash: "4046164356" run: myapp name: myapp-848b5b879b-5k4s4 namespace: default ownerReferences: - apiVersion: apps/v1 blockOwnerDeletion: true controller: true kind: ReplicaSet name: myapp-848b5b879b uid: 8f3f5833-7232-11e9-be24-000c29d142be resourceVersion: "48605" selfLink: /api/v1/namespaces/default/pods/myapp-848b5b879b-5k4s4 uid: 3977b5e7-723a-11e9-be24-000c29d142be spec: #specifications,规格。定义接下来需要创建的资源对象应该具有什么样的特性,应该满足什么样的规范。确保控制器能够被满足。 containers: - image: ikubernetes/myapp:v1 imagePullPolicy: IfNotPresent name: myapp resources: {} terminationMessagePath: /dev/termination-log terminationMessagePolicy: File volumeMounts: - mountPath: /var/run/secrets/kubernetes.io/serviceaccount name: default-token-jvtl7 readOnly: true dnsPolicy: ClusterFirst nodeName: k8snode2 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-jvtl7 secret: defaultMode: 420 secretName: default-token-jvtl7 status: #显示当前资源的当前的状态,只读,由系统维护,而spec由用户定义。如果当前状态和目标状态不一样,k8s就是为了确保每一个资源定义完以后其当前状态无限向目标状态靠近。从而能满足用户期望。 conditions: - lastProbeTime: null lastTransitionTime: 2019-05-08T15:36:44Z status: "True" type: Initialized - lastProbeTime: null lastTransitionTime: 2019-05-08T15:36:46Z status: "True" type: Ready - lastProbeTime: null lastTransitionTime: null status: "True" type: ContainersReady - lastProbeTime: null lastTransitionTime: 2019-05-09T09:10:00Z status: "True" type: PodScheduled containerStatuses: - containerID: docker://0eccbcf513dc608277089bfe2a7b92e1639b1d63ec5d76212a65b30fffa78774 image: ikubernetes/myapp:v1 imageID: docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513 lastState: {} name: myapp ready: true restartCount: 0 state: running: startedAt: 2019-05-08T15:36:45Z hostIP: 192.168.10.12 phase: Running podIP: 10.244.2.14 qosClass: BestEffort startTime: 2019-05-08T15:36:44Z
2、创建资源的方法
a、apiserver在定义资源时仅接收json格式的资源定义,因此,像我们以前使用的run来创建deployment时,run命令会自动将给定的命令转成json格式。
b、yaml格式提供配置清单,apiserver可自动将其转为json,而后再提交;
3、大部分资源的配置清单都由五个组成:
a、apiVersion(group/version):用来指明我们要创建的资源属于哪个资源群组 及版本,k8s把整个api-server所支持的api有多少种分组来进行管理。分了组后,某一组中的改变我们只需要改变一个组就行了,其它组不受影响可以继续使用,另外,还有一个功能,可以让一个组加版本号以后同一个群组不同版本还能够并存。pod是最核心资源,所以其属于核心群组 v1,控制器deployment等属于应用程序管理的核心资源,属于apps/v1。我们集群一般会有三个版本,阿尔法(内测版),贝塔(公测版),stable(稳定版)。
[root@k8smaster ~]# 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 batch/v1 batch/v1beta1 certificates.k8s.io/v1beta1 events.k8s.io/v1beta1 extensions/v1beta1 networking.k8s.io/v1 policy/v1beta1 rbac.authorization.k8s.io/v1 rbac.authorization.k8s.io/v1beta1 scheduling.k8s.io/v1beta1 storage.k8s.io/v1 storage.k8s.io/v1beta1 v1
b、kind:资源类别
c、metadata:元数据,主要提供以下几个字段
1)、name,在同一类别中资源name是唯一的。实例化出来的这个资源类别下的实例的名称。
2)、namespace
3)、labels,每一种类型的资源都可以有标签,标签就是键值数据
4)、annotations,注释
5)、ownerReferences
6)、resourceVersion
7)、uid,唯一标识,由系统自动生成。
8)、selfLink,自引用,就是在我们api中这个资源的格式,比如
selfLink: /api/v1/namespaces/default/pods/myapp-848b5b879b-5k4s4 #在api下v1版本下namespaces为default中名称为
myapp-848b5b879b-5k4s4的pod资源类型
因此每个资源的引用PATH为固定格式 /api/GROUP/VERSION/namespaces/NAMESPACE/TYPE/NAME
...
d、spec:spec可能会嵌套很多其它的二级或三级字段,不同的资源类型其spec中可嵌套的字段不尽相同。其定义用户的期望状态(disired state),资源被创建后状态有可能会不符合条件,因此当前状态会向期望状态靠近。由于有很多字段,因此k8s有内建的格式定义可用explain查看。
[root@k8smaster ~]# 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@k8smaster ~]# kubectl explain pods.metadata KIND: Pod VERSION: v1 RESOURCE: metadata <Object> DESCRIPTION: Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/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. ...
e、status:当前状态(current state),本字段由kubernetes集群维护,用户不能定义它也不能删除它。
四、定义yaml文件
[root@k8smaster manifests]# pwd /root/manifests [root@k8smaster manifests]# ls pod-demo.yaml [root@k8smaster manifests]# cat pod-demo.yaml apiVersion: v1 kind: Pod metadata: name: pod-demo namespace: default labels: #也可以在此处写上{app:myapp,tier:frontend}代替下面两行 app: myapp tier: frontend spec: containers: #是一个列表,具体定义方式如下 - name: myapp image: ikubernetes/myapp:v1 - name: busybox image: busybox:latest command: #也可以写成中括号形式,比如可以在此处写上["/bin/sh","-c","sleep 3600"] - "/bin/sh" - "-c" - "echo ${date} >> /usr/share/nginx/html/index.html;sleep 5" [root@k8smaster manifests]# kubectl create -f pod-demo.yaml Error from server (AlreadyExists): error when creating "pod-demo.yaml": pods "pod-demo" already exists [root@k8smaster manifests]# kubectl get pods -o wide NAME READY STATUS RESTARTS AGE IP NODE myapp-848b5b879b-5k4s4 1/1 Running 0 3d 10.244.2.14 k8snode2 myapp-848b5b879b-bzblz 1/1 Running 0 3d 10.244.1.21 k8snode1 myapp-848b5b879b-hzbf5 1/1 Running 0 3d 10.244.1.22 k8snode1 nginx-deploy-5b595999-d9lv5 1/1 Running 0 3d 10.244.2.4 k8snode2 pod-demo 1/2 CrashLoopBackOff 7 17m 10.244.2.15 k8snode2 [root@k8smaster manifests]# kubectl describe pod pod-demo Name: pod-demo Namespace: default Priority: 0 PriorityClassName: <none> Node: k8snode2/192.168.10.12 Start Time: Thu, 09 May 2019 12:26:59 +0800 Labels: app=myapp tier=frontend Annotations: kubectl.kubernetes.io/last-applied-configuration={"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"labels":{"app":"myapp","tier":"frontend"},"name":"pod-demo ","namespace":"default"},"spec"...Status: Running IP: 10.244.2.15 Containers: myapp: Container ID: docker://b8e4c51d55ac57796b6f55499d119881ef522bcf43e673440bdf6bfe3cd81aa5 Image: ikubernetes/myapp:v1 Image ID: docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513 Port: <none> Host Port: <none> State: Running Started: Thu, 09 May 2019 12:27:00 +0800 Ready: True Restart Count: 0 Environment: <none> Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-jvtl7 (ro) busybox: Container ID: docker://1d3d2c9ab4768c1d9a9dda875c772e9a3a5a489408ad965b09af4d28ee5d5092 Image: busybox:latest Image ID: docker-pullable://busybox@sha256:4b6ad3a68d34da29bf7c8ccb5d355ba8b4babcad1f99798204e7abb43e54ee3d Port: <none> Host Port: <none> Command: /bin/sh -c echo ${date} >> /usr/share/nginx/html/index.html;sleep 5 State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Completed Exit Code: 0 Started: Thu, 09 May 2019 12:44:14 +0800 Finished: Thu, 09 May 2019 12:44:19 +0800 Ready: False Restart Count: 8 Environment: <none> Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-jvtl7 (ro) Conditions: Type Status Initialized True Ready False ContainersReady False PodScheduled True Volumes: default-token-jvtl7: Type: Secret (a volume populated by a Secret) SecretName: default-token-jvtl7 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 Pulled 4d kubelet, k8snode2 Container image "ikubernetes/myapp:v1" already present on machine Normal Created 4d kubelet, k8snode2 Created container Normal Started 4d kubelet, k8snode2 Started container Normal Pulling 4d (x4 over 4d) kubelet, k8snode2 pulling image "busybox:latest" Normal Pulled 4d (x4 over 4d) kubelet, k8snode2 Successfully pulled image "busybox:latest" Normal Created 4d (x4 over 4d) kubelet, k8snode2 Created container Normal Started 4d (x4 over 4d) kubelet, k8snode2 Started container Warning BackOff 4d (x63 over 4d) kubelet, k8snode2 Back-off restarting failed container Normal Scheduled 17m default-scheduler Successfully assigned default/pod-demo to k8snode2
查看日志
[root@k8smaster manifests]# curl 10.244.2.15 Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a> [root@k8smaster manifests]# kubectl logs pod-demo myapp 10.244.0.0 - - [09/May/2019:04:49:18 +0000] "GET / HTTP/1.1" 200 65 "-" "curl/7.29.0" "-" [root@k8smaster manifests]# kubectl logs pod-demo busybox /bin/sh: can't create /usr/share/nginx/html/index.html: nonexistent directory
改变容器busybox的启动命令后启动成功
[root@k8smaster manifests]# cat pod-demo.yaml apiVersion: v1 kind: Pod metadata: name: pod-demo namespace: default labels: #也可以在此处写上{app:myapp,tier:frontend}代替下面两行 app: myapp tier: frontend spec: containers: #是一个列表,具体定义方式如下 - name: myapp image: ikubernetes/myapp:v1 - name: busybox image: busybox:latest command: #也可以写成中括号形式,比如可以在此处写上["/bin/sh","-c","sleep 3600"] - "/bin/sh" - "-c" - "sleep 3600" [root@k8smaster manifests]# kubectl get pods NAME READY STATUS RESTARTS AGE myapp-848b5b879b-5k4s4 1/1 Running 0 3d myapp-848b5b879b-bzblz 1/1 Running 0 3d myapp-848b5b879b-hzbf5 1/1 Running 0 3d nginx-deploy-5b595999-d9lv5 1/1 Running 0 3d pod-demo 2/2 Running 0 1m
进入到容器中
[root@k8smaster manifests]# kubectl exec -it pod-demo -c busybox /bin/sh / # ls bin dev etc home proc root sys tmp usr var / #
五、使用kubectl管理资源有三种用法
1、命令式用法
2、配置清单式用法 (命令式资源清单)
3、使用另外命令(声明式资源清单),确保资源尽可能的向我们声明的状态改变并随时应用。