k8s资源清单基础

资源清单介绍

  创建资源的方法
  apiserver仅接收JSON格式的资源定义
  yaml格式提供配置清单 apiserver可自动把yaml转换成json格式数据

资源清单五个一级字段
   1.apiVersion group/version
     使用kubectl api-versions来获取
   2.kind 资源类别
   3.metadata 元数据
     name
     namespace
     labels
     annotations
  4.spec 期望的状态
  5.satus 当前状态     由k8s维护数据     只能读不能修改   pod控制器的作用就是使各个pod的状态无限的向spec期望的状态靠近

资源清单格式示例

[root@k8s-master mainfests]# vi pod-demo.yml 

apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: default
  labels:
    app: myapp
    tier: frontend
spec:
  containers:
  - name: myapp
    image: ikubernetes/myapp:v1
  - name: busybox
    image: busybox:latest
    command:
    - "/bin/sh"
    - "-c"
    - "sleep 5"
pod-demo.yml

 1.执行创建    kubectl create -f  pod-demo.yml      2.执行删除  kubectl delete -f  pod-demo.yml

 3.查看pod中指定容器日志

[root@k8s-master mainfests]# kubectl logs pod-demo busybox
/bin/sh: can't create /usr/share/nginx/html/index.html: nonexistent directory
View Code
[root@k8s-master mainfests]# kubectl get pods
NAME                          READY     STATUS             RESTARTS   AGE
client                        1/1       Running            0          1d
myapp-74c94dcb8c-dp9t4        1/1       Running            0          45m
myapp-74c94dcb8c-jplgj        1/1       Running            0          45m
myapp-74c94dcb8c-mjjpw        1/1       Running            0          1d
nginx-deploy-5b595999-d7rpg   1/1       Running            0          227d
nginx-deploy-5b595999-xkzqz   1/1       Running            0          45m
pod-demo                      1/2       CrashLoopBackOff   2          3m


[root@k8s-master mainfests]# kubectl describe pods pod-demo
Name:               pod-demo
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               node3/192.168.11.143
Start Time:         Tue, 21 May 2019 18:15:34 +0800
Labels:             app=myapp
                    tier=frontend
Annotations:        <none>
Status:             Running
IP:                 10.244.2.14
Containers:
  myapp:
    Container ID:   docker://ff766f6291cf5e6c3ee92113e8031c59ecffa7871eb9f765602235eda3cc0f30
    Image:          ikubernetes/myapp:v1
    Image ID:       docker-pullable://ikubernetes/myapp@sha256:9c3dc30b5219788b2b8a4b065f548b922a34479577befb54b03330999d30d513
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Tue, 21 May 2019 18:15:45 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-n87jl (ro)
  busybox:
    Container ID:  docker://19d6b5bee5c1fc349a2751bcc560d049ff1972c821ac2d6fac3a09bf8121517d
    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:       ErrImagePull
    Last State:     Terminated
      Reason:       Completed
      Exit Code:    0
      Started:      Tue, 21 May 2019 18:16:23 +0800
      Finished:     Tue, 21 May 2019 18:16:29 +0800
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-n87jl (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  default-token-n87jl:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-n87jl
    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  1m               default-scheduler  Successfully assigned default/pod-demo to node3
  Normal   Pulled     1m               kubelet, node3     Container image "ikubernetes/myapp:v1" already present on machine
  Normal   Created    1m               kubelet, node3     Created container
  Normal   Started    1m               kubelet, node3     Started container
  Normal   Pulled     32s              kubelet, node3     Successfully pulled image "busybox:latest"
  Normal   Created    32s              kubelet, node3     Created container
  Normal   Started    31s              kubelet, node3     Started container
  Warning  Failed     12s              kubelet, node3     Failed to pull image "busybox:latest": rpc error: code = Unknown desc = Error response from daemon: Get https://registry-1.docker.io/v2/library/busybox/manifests/latest: net/http: TLS handshake timeout
  Warning  Failed     12s              kubelet, node3     Error: ErrImagePull
  Normal   Pulling    1s (x3 over 1m)  kubelet, node3     pulling image "busybox:latest"
[root@k8s-master mainfests]# kubectl exec -it pod-demo myapp
Defaulting container name to myapp.
Use 'kubectl describe pod/pod-demo -n default' to see all of the containers in this pod.
rpc error: code = 2 desc = oci runtime error: exec failed: container_linux.go:247: starting container process caused "exec: \"myapp\": executable file not found in $PATH"

command terminated with exit code 126
查看pod异常日志

4.进入pod容器执行命令

[root@k8s-master mainfests]# kubectl exec -it pod-demo -c myapp -- /bin/sh
/ # cat /usr/share/nginx/html/index.html
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
View Code

5.查看清单文件语法帮助

[root@k8s-master ~]# kubectl explain pods.spec
KIND:     Pod
VERSION:  v1

RESOURCE: spec <Object>

DESCRIPTION:
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status

     PodSpec is a description of a pod.

FIELDS:
   activeDeadlineSeconds    <integer>
     Optional duration in seconds the pod may be active on the node relative to
     StartTime before the system will actively try to mark it failed and kill
     associated containers. Value must be a positive integer.

   affinity    <Object>
     If specified, the pod's scheduling constraints

   automountServiceAccountToken    <boolean>
     AutomountServiceAccountToken indicates whether a service account token
     should be automatically mounted.

   containers    <[]Object> -required-
     List of containers belonging to the pod. Containers cannot currently be
     added or removed. There must be at least one container in a Pod. Cannot be
     updated.

   dnsConfig    <Object>
     Specifies the DNS parameters of a pod. Parameters specified here will be
     merged to the generated DNS configuration based on DNSPolicy.

   dnsPolicy    <string>
     Set DNS policy for the pod. Defaults to "ClusterFirst". Valid values are
     'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS
     parameters given in DNSConfig will be merged with the policy selected with
     DNSPolicy. To have DNS options set along with hostNetwork, you have to
     specify DNS policy explicitly to 'ClusterFirstWithHostNet'.

   hostAliases    <[]Object>
     HostAliases is an optional list of hosts and IPs that will be injected into
     the pod's hosts file if specified. This is only valid for non-hostNetwork
     pods.

   hostIPC    <boolean>
     Use the host's ipc namespace. Optional: Default to false.

   hostNetwork    <boolean>
     Host networking requested for this pod. Use the host's network namespace.
     If this option is set, the ports that will be used must be specified.
     Default to false.

   hostPID    <boolean>
     Use the host's pid namespace. Optional: Default to false.

   hostname    <string>
     Specifies the hostname of the Pod If not specified, the pod's hostname will
     be set to a system-defined value.

   imagePullSecrets    <[]Object>
     ImagePullSecrets is an optional list of references to secrets in the same
     namespace to use for pulling any of the images used by this PodSpec. If
     specified, these secrets will be passed to individual puller
     implementations for them to use. For example, in the case of docker, only
     DockerConfig type secrets are honored. More info:
     https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod

   initContainers    <[]Object>
     List of initialization containers belonging to the pod. Init containers are
     executed in order prior to containers being started. If any init container
     fails, the pod is considered to have failed and is handled according to its
     restartPolicy. The name for an init container or normal container must be
     unique among all containers. Init containers may not have Lifecycle
     actions, Readiness probes, or Liveness probes. The resourceRequirements of
     an init container are taken into account during scheduling by finding the
     highest request/limit for each resource type, and then using the max of of
     that value or the sum of the normal containers. Limits are applied to init
     containers in a similar fashion. Init containers cannot currently be added
     or removed. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/init-containers/

   nodeName    <string>
     NodeName is a request to schedule this pod onto a specific node. If it is
     non-empty, the scheduler simply schedules this pod onto that node, assuming
     that it fits resource requirements.

   nodeSelector    <map[string]string>
     NodeSelector is a selector which must be true for the pod to fit on a node.
     Selector which must match a node's labels for the pod to be scheduled on
     that node. More info:
     https://kubernetes.io/docs/concepts/configuration/assign-pod-node/

   priority    <integer>
     The priority value. Various system components use this field to find the
     priority of the pod. When Priority Admission Controller is enabled, it
     prevents users from setting this field. The admission controller populates
     this field from PriorityClassName. The higher the value, the higher the
     priority.

   priorityClassName    <string>
     If specified, indicates the pod's priority. "system-node-critical" and
     "system-cluster-critical" are two special keywords which indicate the
     highest priorities with the former being the highest priority. Any other
     name must be defined by creating a PriorityClass object with that name. If
     not specified, the pod priority will be default or zero if there is no
     default.

   readinessGates    <[]Object>
     If specified, all readiness gates will be evaluated for pod readiness. A
     pod is ready when all its containers are ready AND all conditions specified
     in the readiness gates have status equal to "True" More info:
     https://github.com/kubernetes/community/blob/master/keps/sig-network/0007-pod-ready%2B%2B.md

   restartPolicy    <string>
     Restart policy for all containers within the pod. One of Always, OnFailure,
     Never. Default to Always. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy

   schedulerName    <string>
     If specified, the pod will be dispatched by specified scheduler. If not
     specified, the pod will be dispatched by default scheduler.

   securityContext    <Object>
     SecurityContext holds pod-level security attributes and common container
     settings. Optional: Defaults to empty. See type description for default
     values of each field.

   serviceAccount    <string>
     DeprecatedServiceAccount is a depreciated alias for ServiceAccountName.
     Deprecated: Use serviceAccountName instead.

   serviceAccountName    <string>
     ServiceAccountName is the name of the ServiceAccount to use to run this
     pod. More info:
     https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/

   shareProcessNamespace    <boolean>
     Share a single process namespace between all of the containers in a pod.
     When this is set containers will be able to view and signal processes from
     other containers in the same pod, and the first process in each container
     will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both
     be set. Optional: Default to false. This field is alpha-level and is
     honored only by servers that enable the PodShareProcessNamespace feature.

   subdomain    <string>
     If specified, the fully qualified Pod hostname will be
     "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>". If not
     specified, the pod will not have a domainname at all.

   terminationGracePeriodSeconds    <integer>
     Optional duration in seconds the pod needs to terminate gracefully. May be
     decreased in delete request. Value must be non-negative integer. The value
     zero indicates delete immediately. If this value is nil, the default grace
     period will be used instead. The grace period is the duration in seconds
     after the processes running in the pod are sent a termination signal and
     the time when the processes are forcibly halted with a kill signal. Set
     this value longer than the expected cleanup time for your process. Defaults
     to 30 seconds.

   tolerations    <[]Object>
     If specified, the pod's tolerations.

   volumes    <[]Object>
     List of volumes that can be mounted by containers belonging to the pod.
     More info: https://kubernetes.io/docs/concepts/storage/volumes
View Code

标签操作说明

  任何k8s资源都可以打上标, 例如  pod  节点  service等

  标签选择器
       等值关系 =     ==       !=
       集合关系  key in|notin    (value1,value2)      !key 不存在此key

  许多资源支持内嵌字段
     matchLabels 直接给定键值
     matchExpressions 基于给定的表达式来定义使用的标签选择器 {key:"KEY",operator:"OPERATOR",values:[val1,val2,...]}

     操作符

        In, NotIn:              values字段的值为非空列表

        Exists,NotExists:  values字段的值必须为空列表

   pod标签过滤器

[root@k8s-master ~]# kubectl label pods pod-demo release=canary
pod/pod-demo labeled
[root@k8s-master ~]# kubectl get pods -l app --show-labels
NAME       READY     STATUS    RESTARTS   AGE       LABELS
pod-demo   2/2       Running   0          1m        app=myapp,release=canary,tier=frontend

[root@k8s-master ~]# kubectl label pods pod-demo release=canary
pod/pod-demo labeled
[root@k8s-master ~]# kubectl get pods -l app --show-labels
NAME       READY     STATUS    RESTARTS   AGE       LABELS
pod-demo   2/2       Running   0          1m        app=myapp,release=canary,tier=frontend

[root@k8s-master ~]# kubectl get pods --show-labels
NAME                          READY     STATUS    RESTARTS   AGE       LABELS
client                        1/1       Running   0          1d        run=client
myapp-74c94dcb8c-dp9t4        1/1       Running   0          4h        pod-template-hash=3075087647,run=myapp
myapp-74c94dcb8c-jplgj        1/1       Running   0          4h        pod-template-hash=3075087647,run=myapp
myapp-74c94dcb8c-mjjpw        1/1       Running   0          1d        pod-template-hash=3075087647,run=myapp
nginx-deploy-5b595999-d7rpg   1/1       Running   0          228d      pod-template-hash=16151555,run=nginx-deploy
nginx-deploy-5b595999-xkzqz   1/1       Running   0          4h        pod-template-hash=16151555,run=nginx-deploy
pod-demo                      2/2       Running   0          6m        app=myapp,release=canary,tier=frontend


[root@k8s-master ~]# kubectl get pods -l release
NAME       READY     STATUS    RESTARTS   AGE
pod-demo   2/2       Running   0          4m
[root@k8s-master ~]# kubectl get pods -l release,app
NAME       READY     STATUS    RESTARTS   AGE
pod-demo   2/2       Running   0          4m
[root@k8s-master ~]# ^C
[root@k8s-master ~]# kubectl get pods -l release==canary
NAME       READY     STATUS    RESTARTS   AGE
pod-demo   2/2       Running   0          6m
View Code

  添加标签 

     kubectl   label    pods    pod-demo    release=canary

  查看标签列表信息

     kubectl  get  nodes   --show-labels

实现创建的pod运行到指定的节点上      通过节点标签选择器nodeSelector     nodeName节点名称选择器

[root@k8s-master ~]# kubectl get pods -o wide
NAME   
pod-demo                      2/2       Running   0          29m       10.244.2.16   node3
pod-demo被随机分配到node3节点上 

[root@k8s-master mainfests]# kubectl get nodes --show-labels
NAME         STATUS    ROLES     AGE       VERSION   LABELS
k8s-master   Ready     master    228d      v1.11.1   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=k8s-master,node-role.kubernetes.io/master=
node2        Ready     <none>    228d      v1.11.1   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node2
node3        Ready     <none>    228d      v1.11.1   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node3

给node2添加一个独立的标签
[root@k8s-master mainfests]# kubectl label nodes node2 disktype=ssd
node/node2 labeled
[root@k8s-master mainfests]# kubectl get nodes --show-labels
NAME         STATUS    ROLES     AGE       VERSION   LABELS
k8s-master   Ready     master    228d      v1.11.1   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=k8s-master,node-role.kubernetes.io/master=
node2        Ready     <none>    228d      v1.11.1   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disktype=ssd,kubernetes.io/hostname=node2
node3        Ready     <none>    228d      v1.11.1   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node3


[root@k8s-master mainfests]# vi pod-demo.yml 

apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: default
  labels:
    app: myapp
    tier: frontend
spec:
  containers:
  - name: myapp
    image: ikubernetes/myapp:v1
  - name: busybox
    image: busybox:latest
    command:
    - "/bin/sh"
    - "-c"
    - "sleep 50000"
  nodeSelector:
    disktype: ssd

[root@k8s-master mainfests]# kubectl delete -f pod-demo.yml 
pod "pod-demo" deleted
[root@k8s-master mainfests]# kubectl create -f pod-demo.yml 
pod/pod-demo created


[root@node2 ~]# docker ps
CONTAINER ID        IMAGE                                                                             COMMAND                  CREATED             STATUS              PORTS               NAMES
87df5370d6d2        busybox@sha256:4b6ad3a68d34da29bf7c8ccb5d355ba8b4babcad1f99798204e7abb43e54ee3d   "/bin/sh -c 'sleep..."   15 seconds ago      Up 14 seconds                           k8s_busybox_pod-demo_default_cd77d89a-7bd4-11e9-9c03-000c2927f194_0
9f1838fa3793        d4a5e0eaa84f                                                                      "nginx -g 'daemon ..."   28 seconds ago      Up 27 seconds                           k8s_myapp_pod-demo_default_cd77d89a-7bd4-11e9-9c03-000c2927f194_0
View Code

猜你喜欢

转载自www.cnblogs.com/yxh168/p/10898379.html