使用配置清单创建资源

定义pod时使用yaml格式

master ~]# kubectl get pod

NAME                           READY   STATUS      RESTARTS   AGE
client / Error 10d
client1 / Completed 9d
client2 / Error 7h13m
client3 / Running 5h57m
myapp-5bc569c47d-5cdpw / Running 3h20m
myapp-5bc569c47d-c4gr2 / Running 3h20m
myapp-5bc569c47d-njr5w / Running 3h20m
nginx-deploy-55d8d67cf-hlj9v / Running 10d

master ~]# kubectl get pod myapp-5bc569c47d-5cdpw -o yaml  //以yaml格式输出pod信息

apiVersion: v1   //这里的值一般是group/version,这里省略了group名,就表示核心组
kind: Pod //资源类别
metadata: //元数据
creationTimestamp: "2019-06-14T05:32:03Z"
generateName: myapp-5bc569c47d-
labels:
pod-template-hash: 5bc569c47d
run: myapp
name: myapp-5bc569c47d-5cdpw
namespace: default
ownerReferences:
- apiVersion: apps/v1
blockOwnerDeletion: true
controller: true
kind: ReplicaSet
name: myapp-5bc569c47d
uid: bcd43ea4-8e43-11e9-a017-000c29cef804
resourceVersion: ""
selfLink: /api/v1/namespaces/default/pods/myapp-5bc569c47d-5cdpw
uid: bd573709-8e65-11e9-a017-000c29cef804
spec: //规格,即定义接下来所要创建的资源对象所具有的特性,或者满足的规范。可以让用户定义资源对象所处的目标状态
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-fckpp
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: node01
priority:
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
serviceAccount: default
serviceAccountName: default
terminationGracePeriodSeconds:
tolerations:
- effect: NoExecute
key: node.kubernetes.io/not-ready
operator: Exists
tolerationSeconds:
- effect: NoExecute
key: node.kubernetes.io/unreachable
operator: Exists
tolerationSeconds:
volumes:
- name: default-token-fckpp
secret:
defaultMode:
secretName: default-token-fckpp
status: //显示当前资源的当前状态,如果当前状态与目标状态不一致,则需要以目标状态为准
conditions:
- lastProbeTime: null
lastTransitionTime: "2019-06-14T05:32:03Z"
status: "True"
type: Initialized
- lastProbeTime: null
lastTransitionTime: "2019-06-14T05:32:05Z"
status: "True"
type: Ready
- lastProbeTime: null
lastTransitionTime: "2019-06-14T05:32:05Z"
status: "True"
type: ContainersReady
- lastProbeTime: null
lastTransitionTime: "2019-06-14T05:32:03Z"
status: "True"
type: PodScheduled
containerStatuses:
- containerID: docker://0cc8d93c55ee79efe9d7bf4117e1c59db309be4fb498a0486317d33413066d8b
image: ikubernetes/myapp:v1
imageID: docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513
lastState: {}
name: myapp
ready: true
restartCount:
state:
running:
startedAt: "2019-06-14T05:32:04Z"
hostIP: 192.168.184.142
phase: Running
podIP: 10.244.3.9
qosClass: BestEffort
startTime: "2019-06-14T05:32:03Z"

创建资源的方法:

apiserver仅接收JSON格式的资源定义;

yaml格式提供配置清单,apiserver可自动将其转为json格式,而后再提交;

大部分资源的配置清单(5个一级字段):

1、apiServer:group/version 指明创建的资源属于哪个api群组及其版本

master ~]# kubectl api-versions  //查看所有版本
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1 //控制器deployment等属于应用程序管理的核心组资源,属于本组
apps/v1beta1
apps/v1beta2
........
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
.......
v1 //主版本,属于核心群组,pod是最核心的资源,属于核心群组,

alpha版:内部测试版  http://www.ttlsa.com/linux/alpha-beta-rc/

beta版:公开测试版

stable版:稳定版

2、kind:资源类别,用来标记创建资源的类型,比如资源是pod或者是deployment或者service等

3、metadata:元数据

name

namespace

labels        标签

annotations   资源注解

每个资源的引用PATH

/api/GROUP/VERSION/namespaces/NAMESPACE/TYPE/NAME   //TPYE是资源类别

例如:selfLink: /api/v1/namespaces/default/pods/myapp-5bc569c47d-5cdpw

4、spec:不同的资源类型,它的spec类型是不尽相同的,它是用来定义用户期望的目标状态disired state

5、status:当前状态,current state。本字段由kubernetes集群维护,用户不能删除、定义它

master ~]# kubectl explain pods  //pods资源如何定义

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

查看二级字段如何定义

master ~]# 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> //表示映射,由三级组成的映射,映射是另外一种json格式的数组,
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>
...... creationTimestamp <string> ...... deletionGracePeriodSeconds <integer> ..... deletionTimestamp <string>
......
https://git.k8s.io/community/contributors/devel/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. generateName <string> .....
https://git.k8s.io/community/contributors/devel/api-conventions.md#idempotency generation <integer>
A sequence number representing a specific generation of the desired state.
Populated by the system. Read-only. initializers <Object> //表示可以被嵌套三级字段 .... labels <map[string]string>
.... 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. This field is alpha and can be
changed or removed without notice. name <string> ...... namespace <string> ....
ownerReferences <[]Object>
.... resourceVersion <string> .....
https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency selfLink <string>
SelfLink is a URL representing this object. Populated by the system.
Read-only. uid <string>
....

master ~]# kubectl explain pods.spec.containers.livenessProbe  //可以查询多级字段定义内容

示例:基于yaml格式的配置文件,定义一个自助式pod资源

两个容器运行在一个pod中

[root@master ~]# mkdir manifests
[root@master ~]# cd !$
cd manifests
[root@master manifests]# vim pod-demo.yaml

   apiVersion: v1
kind: Pod
metadata:
name: pod-demo
namespace: default
labels: //映射数据可以使用{},例如labels: {app:myapp, tier:frontend};
app: myapp
tier: frontend
spec:
containers:
- name: myapp
image: ikubernetes/myapp:v1
- name: busybox //由于命令错误,就将busybox删除了
image: busybox:latest
command: //列表数据可以使用[],例如["/bin/sh","-c","sleep 3600"]
- "/bin/sh"
- "-c"
- "echo $(date) >> /usr/share/nginx/html/index.html; sleep 5" --> 由于myapp和busybox的文件系统不是同一个,所以可将此处修改为: "- sleep 3600"

master manifests]# kubectl create -f pod-demo.yaml   //-f表示从文件中加载创建pod

pod/pod-demo created

master manifests]# kubectl get pods  //查看运行的pod

NAME                           READY   STATUS      RESTARTS   AGE
client3 / Running 13h
myapp-5bc569c47d-5cdpw / Running 10h
myapp-5bc569c47d-c4gr2 / Running 10h
myapp-5bc569c47d-njr5w / Running 10h
nginx-deploy-55d8d67cf-hlj9v / Running 10d
pod-demo / Running 6s

master manifests]# kubectl describe pods pod-demo //pod是类型,pod-demo是名称,先指明资源类型再指明名称,因为资源名称只在类型下唯一

Name:               pod-demo
Namespace: default
Priority:
PriorityClassName: <none>
Node: node03/192.168.184.144
Start Time: Sat, Jun :: +
Labels: app=myapp
tier=frontend
Annotations: <none>
Status: Pending
IP: 10.244.1.10
Containers:
myapp:
Container ID: docker://bf8723299d620b47ddcd8073c256d057d32408d9caf46855a12876bd3c836d95
Image: ikubernetes/myapp:v1
Image ID: docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513
Port: <none>
Host Port: <none>
State: Running
Started: Sat, Jun :: +
Ready: True
Restart Count:
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-fckpp (ro)
busybox:
Container ID:
Image: busybox:latest
Image ID:
Port: <none>
Host Port: <none>
Command:
/bin/sh
-c
echo $(date) >> /usr/share/nginx/html/index.html; sleep
State: Waiting
Reason: ErrImagePull
Ready: False
Restart Count:
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-fckpp (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
default-token-fckpp:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-fckpp
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 96s default-scheduler Successfully assigned default/pod-demo to node03
Normal Pulled 93s kubelet, node03 Container image "ikubernetes/myapp:v1" already present on machine
Normal Created 93s kubelet, node03 Created container myapp
Normal Started 93s kubelet, node03 Started container myapp
Normal Pulling 93s kubelet, node03 Pulling image "busybox:latest"
Warning Failed 2s kubelet, node03 Failed to pull image "busybox:latest": rpc error: code = Unknown desc = context canceled
Warning Failed 2s kubelet, node03 Error: ErrImagePull
Normal BackOff 2s kubelet, node03 Back-off pulling image "busybox:latest"
Warning Failed 2s kubelet, node03 Error: ImagePullBackOff

查看pod的日志

[root@master manifests]# curl 10.244.1.10
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
[root@master manifests]# kubectl logs pod-demo myapp
10.244.0.0 - - [/Jun/::: +] "GET / HTTP/1.1" "-" "curl/7.29.0" "-"
[root@master manifests]# kubectl logs pod-demo busybox //busybox创建容器时出现错误
/bin/sh: can't create /usr/share/nginx/html/index.html: nonexistent directory //这里显示文件路径出现错误,因为myapp和busybox这两个容器虽然运行再同一个pod,
但他们的文件系统是隔离的,应该在pod上创建一个存储卷,将两个容器同时挂载,这样执行的时候才能看到同一个文件。

master manifests]# kubectl exec -it pod-demo -c myapp -- /bin/sh  //-c是指明容器名称

/ # ls
bin dev etc home lib media mnt proc root run sbin srv sys tmp usr var
/ # ls /usr/share
GeoIP man misc nginx
/ # ls /usr/share/nginx/
html
/ # ls /usr/share/nginx/html
50x.html index.html
/ # cat /usr/share/nginx/html/index.html
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
/ # exit

master ~]# kubectl delete pod pod-demo  //先删除pod,进行排错
     pod "pod-demo" deleted

master manifests]# vim pod-demo.yaml

     command:
- "/bin/sh"
- "-c"
- "sleep 3600" //此处进行了修改

master manifests]# kubectl create -f pod-demo.yaml
pod/pod-demo created

上述演示了在k8s上一个镜像运行为pod的容器,它的默认命令是如何自定义的。

基于清单删除资源

master manifests]# kubectl delete -f pod-demo.yaml   //表示仅删除yaml文件中所定义的资源,另外可以基于清单再次创建资源

5、kubernetes资源清单定义入门的更多相关文章

  1. kubernetes系列06—kubernetes资源清单定义入门

    本文收录在容器技术学习系列文章总目录 1.认识kubernetes资源 1.1 常用资源/对象 workload工作负载型资源:pod,ReplicaSet,Deployment,StatefulSe ...

  2. Kubernetes 学习5 kubernetes资源清单定义入门

    一.kubernetes是有一个restful风格的 API,把各种操作对象都一律当做资源来管理.并且可通过标准的HTTP请求的方法 GET,PUT,DELETE,POST,等方法来完成操作,不过是通 ...

  3. kubernetes 资源清单定义入门

    k8s中的资源 什么叫资源? k8s中所有的内容都抽象为资源, 资源实例化之后,叫做对象 在k8s中有哪些资源? 工作负载型资源(workload): Pod ReplicaSet Deploymen ...

  4. 4、kubernetes资源清单快速入门190625

    一.资源清单概念 资源/对象的类型 工作负载型资源:Pod, ReplicaSet, Deployment, StatefulSet, DaemonSet, Job, Cronjob, ... 服务发 ...

  5. Kubenetes 资源清单定义入门

    Kubernetes 常用资源 资源  对象 工作负载型资源对象(workload): Pod  Replicaset  ReplicationController  Deployments Stat ...

  6. k8s学习笔记之四:资源清单定义入门

    第一章.k8s中的资源 1.什么叫资源? k8s中所有的内容都抽象为资源, 资源实例化之后,叫做对象 2.在k8s中有哪些资源? 工作负载型资源(workload): Pod ReplicaSet D ...

  7. 04-kubernetes 资源清单定义入门

    目录 资源对象 创建资源的方法 清单帮助命令 创建测试清单 资源的三种创建方式 资源对象 workload:Pod, ReplicaSet, Deployment, StatefulSet, Daem ...

  8. (四)Kubernetes 资源清单定义

    Kubernetes常用资源对象 依据资源的主要功能作为分类标准,Kubernetes的API对象大体可分为五个类别,如下: 类型 名称 工作负载(Workload) Pod.ReplicaSet.D ...

  9. 四,k8s集群资源清单定义入门

    目录 资源对象 创建资源的方法 清单帮助命令 创建测试清单 资源的三种创建方式 资源对象 workload:Pod, ReplicaSet, Deployment, StatefulSet, Daem ...

随机推荐

  1. linux 命令技巧(转)--history

    本文介绍一些关于bash的能够提高效率的技巧,主要是关于历史命令操作和一些快捷键,让你在命令行下工作效率翻倍. 1.history-----最基本的查看历史命令 2.!n-----编号为n的历史命令 ...

  2. java使用策略模式代替if/else

    平时在开发中避免不了使用大量的if else语句,但过多层的if else对于性能有很大的开销,类似如下代码 public class MainStart { public static void m ...

  3. 第七章 路由 76 路由传参-使用params方式传递路由参数

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  4. FutureWarning: get_value is deprecated and will be removed in a future release. Please use .at[] or .iat[] accessors instead print(labels_df.get_value(patients,col=1))

    这是因为pandas的版本高了,0.21之后就已经将这个方法干掉了.直接装成0.20之前的就好

  5. php类相关知识----抽象类

    <?php //抽象类存在的目的是被继承,而不是用来被实现 abstract class wenwajiao { //抽象类中一定要有抽象方法,而且一定要被实现 abstract public ...

  6. 07 saltstack生产实例-mysql主从

    1.服务部署 .服务部署 抽象:功能模块 redis 安装.配置.启动 mysql 安装.配置(my.cnf可以统一 目录默认配置可以统一) master: server_id slave: serv ...

  7. 【Weblogic】-weblogic查看版本及升级

    一.查看weblogic版本 1. cd /weblogic/bea/wlserver_10.3/server/lib 2. java -cp weblogic.jar weblogic.versio ...

  8. linux中telnet后退出连接窗口

    [root@a cron]# telnet www.baidu.com 80Trying 115.239.211.112...Connected to www.baidu.com.   #显示conn ...

  9. 网络编程-UDP echo server

    1. UDP简介 UDP 和TCP 的区别包括 1. 面向字节流和面向报文 2. TCP必须要建立连接后才能进行数据交换,但是UDP则并没有连接的建立和释放过程.面向字节流说明,tcp报文段(segm ...

  10. Chef 组件

    Chef是一家自动化公司.自2008年成立以来,我们一直在将开发人员和系统管理员与我们的同名产品Chef Infra联系在一起.多年来,我们所说的自动化已经扩展了.今天,Chef为基础设施和应用程序提 ...