K8S(三)-资源清单

 资源:

kubernetes把资源实例化之后称为对象,常见的资源有:

  • workload: Pod,ReplicaSet,Deployment,StatefulSet DaemonSet,Job,Cronjob,...
  • 服务发现及均衡: service,ingress
  • 配置与存储:Volume(云端存储,分布式存储,nfs,glastfs), CSI容器存储接口,configmap(配置中心),secret(保存敏感信息),DownwordAPI
  • 集群级资源: Namespace, Node, Role, ClusterRole, RoleBanding, ClusterRoleBanding
  • 元数据型资源: HPA,  PodTemlate,  limitRange

查看pod的资源清单:

# kubectl get pod myapp-5bc569c47d-5cvcx -o yaml

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2019-10-09T03:11:08Z"
  generateName: myapp-5bc569c47d-
  labels:
    pod-template-hash: 5bc569c47d
    release: stable
    run: myapp
  name: myapp-5bc569c47d-5cvcx
  namespace: default
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: myapp-5bc569c47d
    uid: 70044b8c-ea42-11e9-9460-fa163e359251
  resourceVersion: "2283413"
  selfLink: /api/v1/namespaces/default/pods/myapp-5bc569c47d-5cvcx
  uid: 70151f83-ea42-11e9-9460-fa163e359251
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-bpr69
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: szgl-szgl-baol1-test03-8144.jpushoa.com
  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-bpr69
    secret:
      defaultMode: 420
      secretName: default-token-bpr69
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2019-10-09T03:11:08Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2019-10-09T03:11:55Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2019-10-09T03:11:55Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2019-10-09T03:11:08Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://67f6558d7f14f73a0bc67cf06084a6031896a230b8904b3738c1d48738cd4c2f
    image: ikubernetes/myapp:v1
    imageID: docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513
    lastState: {}
    name: myapp
    ready: true
    restartCount: 0
    state:
      running:
        startedAt: "2019-10-09T03:11:54Z"
  hostIP: 172.17.8.144
  phase: Running
  podIP: 10.244.1.8
  qosClass: BestEffort
  startTime: "2019-10-09T03:11:08Z"
View Code
apiVersion:  v1  # group/version,如果没有给定group名称那么默认为core,可以使用kubectl api-versions获取当前k8s版本上所有的apiVersion版本信息(每个版本可能不同)
kind: Pod   #资源类别,可以是Deployment、Service、Ingress等
metadata:   #资源元数据
    name
    namespace
    labels
    annotations
spec:  # 期望的状态,定义资源对象应该具有的特性,比如容器是几个,每个容器用什么镜像创建,容忍度,污点等,然后靠控制器来确保状态被满足
status#显示当前状态。只读。本字段用户不能定义,是由kubenetes集群来维护

 每个资源的引用PATH

/api/GROUP/VERSION/namespaces/NAMESPACE/TYPE/NAME

创建资源的方法:

  • apiserver在定义资源时,仅接收JSON格式的资源定义。像使用run来创建deployment时,run命令会自动把内容转成json。
  • 利用yaml格式提供配置清单,apiserver可自动将其转为json格式,而后再提交并执行。

查看资源的详细说明:
# kubectl explain ingress
# kubectl explain pod
# 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/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/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/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>
     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/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>
     An initializer is a controller which enforces some system invariant at
     object creation time. This field is a list of initializers that have not
     yet acted on this object. If nil or empty, this object has been completely
     initialized. Otherwise, the object is considered uninitialized and is
     hidden (in list/watch and get calls) from clients that haven't explicitly
     asked to observe uninitialized objects. When an object is created, the
     system will populate this list with the current set of initializers. Only
     privileged users may set or modify this list. Once it is empty, it may not
     be modified further by any user. DEPRECATED - initializers are an alpha
     field and will be removed in v1.15.

   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. This field is alpha and can be
     changed or removed without notice.

   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/api-conventions.md#concurrency-control-and-consistency

   selfLink    <string>
     SelfLink is a URL representing this object. Populated by the system.
     Read-only.

   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
View Code

 字段的格式说明:

-required-    表示必选字段
<string>     字符串类型
<integer>    整型
<Object>    表示需要嵌套多层字段
<[]Object>   对象列表
<map[string]string>   映射,k:v格式
<boolean>    布尔类型

 

使用配置清单创建pod

# cat test-pod.yml 
apiVersion: v1
kind: Pod
metadata:
  name: test-pod
  namespace: default
  labels:
    app: myapp
    project: dev
spec:
  containers:             #一个pod中运行两个容器
  - name: myapp
    image: ikubernetes/myapp:v1
  - name: busybox
    image: busybox:latest
    command:
      - "/bin/sh"
      - "-c"
      - "sleep 3600"

创建:

 #  kubectl create -f test-pod.yaml 
pod/test-pod created

查看:

# kubectl get pods -o wide
NAME      READY   STATUS    RESTARTS   AGE   IP            NODE     NOMINATED NODE   READINESS GATES
test-pod  2/2     Running   0          31s   10.244.1.39   node01   <none>           <none>

# kubectl describe pods test-pod  可以看到起来了两个容器

 访问pod

# curl 10.244.1.39
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>

查看访问日志:

# kubectl logs test-pod -c myapp
10.244.0.0 - - [23/Oct/2019:01:47:18 +0000] "GET / HTTP/1.1" 200 65 "-" "curl/7.29.0" "-"

 删除清单定义

# kubectl delete -f test-pod.yml
pod "test-pod" deleted

 

 

posted @ 2019-11-12 21:01  卡布爱学习  阅读(393)  评论(0编辑  收藏  举报