2-1、kubernetes基础

kubernetes基础
master/node:
    master:API server,Scheduler,Controller-Manager,etcd
    node:kubelet,docker,kube-proxy
POD,Label,Label Selector
    Label:key=value
    Label seclector:
Pod:
    自主式pod
    控制器管理的Pod:
        Replication Controller
        ReplicaSet
        Deployment
        StatefulSet
        DaemonSet
        Job,Ctonjob
CNI:
    flannel:网络配置
    calico:网络配置,网络策略
    canel:


资源:对象
workload:运行应用程序,提供服务,如Pod,ReplicaSet,Deployoment,StatefulSet,DaemonSet,Job,Cronjob
服务发现及均衡:Service,Ingress,
配置及存储:Volume,CSI
    COnfigMap.Secret
    DownwardAPI
集群级资源:
    Namespace,Node,Role,ClusterRole,ClusterRoleBinding
元数据型资源:
    HPA,PodTemplate,LimitRange


创建资源的方法:
    apiserver仅接收json格式的资源定义;
    yaml格式提供的配置清单,apiserver可自动将其转换为json格式

大部分资源配置清单结构:
    apiVserfion:group/version
    kind:资源类别
       metadata:元数据
        labels:标签
        name:
        namespace:
        annotations

        每个资源引用的PATH
               /api/GROUP/VERSION/namespaces/NAMESPACE/TYPE/NAME
               /api/v1/namespaces/default/pods/nginx-deploy-54d6d94f75-qn2tq
     spc:期望的状态,disired state
     status:当前的状态,current state,本字段有kubernetes集群维护;

kubectl explain pods    #查看Pod有字段信息
kubectl explain pods.apiVeersion    #查看Pod的apiVeersion有字段信息


标签:
    key=value
        key:字母、数字、下划线....
        value:可以为空,只能字母,数字开头及结尾
标签选择器:
    等值关系:=,==,!=
    集合关系:
        KEY in (value1,value3,...)
        KEY notin (value1,value3,...)
        KEY
        !KEY
许多资源支持内嵌字段定义其使用的标签选择器:
    mathchLabels:直接给定键值
    mathchExpressions:基于给定的表达式来定义使用标签选择器,{key:"KEY",    operator:"OPERATOR",values:[VALUE1,VALUE2,...]}
        操作符:
            In,NotIn:values字段的值必须为非空列表;
            Exists,NotExists:values字段的值吸引为空列表;

节点选择器:
    nodeSelector <map[string] string>
    nodeSelector:
        resource_type:NA_Container

annotations:资源注解
    与label不同的地方在于,它不能用于挑选资源对象,仅用于为对象提供“元数据”。

Pod生命周期:
    状态:Pending,Running,Failed,Succeeded,Unknown
    创建Pod:api,etcd,schdule
    Pod生命中的重要行为;
        初始化容器;
        容器探测:liveness probe:探测pod是否存活
                  readiness probe:探测容器能否提供服务

restartPolicy:针对pod
    Always,OnFailure,Never;default to always

探针类型有三种(针对container):kubectl explain pods.spec.containers
    ExecAction,TCPSocketAction,HTTPGetAction
    


spec:
    containers
    nodeSelector
    nodeName
    restartPolicy
        Always,Never,OnFailure

    containers:
        name
        image
        imagePullPolicy: Always,Never,IfNotPresent
        ports:
            name
            containerPort
         livenessProbe
         readinessProbe
         liftcycle
    ExecAction:exec
    TCPSocketAction:tcpSocket
    HTTPGetAction:httpGet


------------------------
kubectl api-versions  查看api版本信息   @aiph:内测版;beta:公测版;stable:稳定版
# kubectl api-versions
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
......


#自定义pod  yaml文件
# vi pod-demo.yaml
apiVsersion: v1
kind: Pod
metadata: 
    name: pod-demo
    namespace: default
    labels:
        app: myapp
        tier: frontend
    annotations:
        cluster.com/created-by: "cluster domain"
spec:
    containers:
    - name: myapp
      image: ikubernetes/myapp:v1
      ports:
      - name: http
        containerPort: 80
      - name: https
        containerPort: 443
    nodeSelector:
        resource_type:NA_Container
    - name: busybox
      image: busybox:latest
      imagePullPolicy: IfNotPresent
      command:  #或["/bin/bash","-c","sleep 5"]
      - "/bin/bash"
      - "-c"
      - "sleep 5"
      command: ["/bin/sh","-C","touch /tmp/checkhealthy","sleep 30","rm -rf /tmp/checkhealthy","sleep 360"]
      livenessProbe:
          exec:
              command:["test","-e","/tmp/checkhealthy"]
          initialDelaySeconds: 1
          periodSeconds: 3
          httpGet:
              port: http
              path: /index.html
          initialDelaySeconds: 1
          periodSeconds: 3
      readinessProbe:
          httpGet:
              port: http
              path: /index.html
          initialDelaySeconds: 1
          periodSeconds: 3
      lifecycle:
          postStart:
               exec:
                  command:["/bin/sh","-c","mkdir -p /data/web/html;echo Web_Home_Page >>/data/web/html/index.html"]
          command: ["/bin/httpd"]
          args: ["-f","-h /data/web/html"]
          initialDelaySeconds: 1
          periodSeconds: 3



--------

根据自定义的yaml创建pod:
# kubectl create -f pod-demo.yaml
# kubectl get pods
pod-demo       1/2     CrashLoopBackOff   6     8m31s   app=myapp,tier=frontend

# kubectl describe pod pod-demo

# kubectl logs pod-demo myapp  #查看日志
# curl 10.244.3.3  #访问刚创建的pod-demo中的myapp
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
# kubectl logs pod-demo busybox

删除yaml自定义创建的Pod
# kubectl delete -f pod-demo.yaml

根据标签过滤:
# kubectl get pods -l app  过滤出标签中带有app的
# kubectl get pods -l app --show-labels
NAME       READY   STATUS              RESTARTS   AGE   LABELS
pod-demo   1/2     RunContainerError   21         84m   app=myapp,tier=frontend


# kubectl get pods -L app,run    #多个标签
NAME                            READY   STATUS             RESTARTS   AGE    APP     RUN
nginx-deploy-54d6d94f75-qn2tq   1/1     Running            0          5h2m           nginx-deploy
pod-demo                        1/2     CrashLoopBackOff   21         85m    myapp 


打标签或修改标签:
kubectl label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
# kubectl get pods --show-labels
NAME                            READY   STATUS         RESTARTS   AGE    LABELS
nginx-deploy-54d6d94f75-qn2tq   1/1     Running        0          5h8m   pod-template-hash=54d6d94f75,run=nginx-deploy
pod-demo                        1/2     ErrImagePull   3          2m7s   app=myapp,tier=frontend

# kubectl label pod pod-demo release=cannary
# kubectl get pods --show-labels
NAME                            READY   STATUS         RESTARTS   AGE     LABELS
nginx-deploy-54d6d94f75-qn2tq   1/1     Running        0          5h10m   pod-template-hash=54d6d94f75,run=nginx-deploy
pod-demo                        1/2     ErrImagePull   3          4m7s    app=myapp,release=cannary,tier=frontend

# kubectl label pod pod-demo release=stable --overwrite
# kubectl get pods --show-labels
NAME                            READY   STATUS             RESTARTS   AGE     LABELS
nginx-deploy-54d6d94f75-qn2tq   1/1     Running            0          5h12m   pod-template-hash=54d6d94f75,run=nginx-deploy
pod-demo                        1/2     CrashLoopBackOff   3          6m1s    app=myapp,release=stable,tier=frontend


节点选择器:
nodeSelector在yaml文件中,与 containers字段平级,
# kubectl label node vm1.cluster.com resource_type=NA_Container
在yaml文件中指定pod将分配到指定类型的节点上:如pod将被分配到label中有NA_Container的节点上
    nodeSelector:
        resource_type:NA_Container

分配到指定的节点上:
nodeName string


资源配置清单结构:pod详细信息
# kubectl get pod nginx-deploy-54d6d94f75-qn2tq -o yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2019-04-06T00:38:24Z"
  generateName: nginx-deploy-54d6d94f75-
  labels:
    pod-template-hash: 54d6d94f75
    run: nginx-deploy
  name: nginx-deploy-54d6d94f75-qn2tq
  namespace: default
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: nginx-deploy-54d6d94f75
    uid: e68bfe73-57c6-11e9-835d-000c29447357
  resourceVersion: "72483"
  selfLink: /api/v1/namespaces/default/pods/nginx-deploy-54d6d94f75-qn2tq
  uid: 49651e53-5804-11e9-835d-000c29447357
spec:
  containers:
  - image: nginx:1.14-alpine
    imagePullPolicy: IfNotPresent
    name: nginx-deploy
    ports:
    - containerPort: 8080
      protocol: TCP
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-kctgz
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: vm2.cluster.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-kctgz
    secret:
      defaultMode: 420
      secretName: default-token-kctgz
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2019-04-06T11:29:30Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2019-04-06T11:29:51Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2019-04-06T11:29:51Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2019-04-06T02:26:49Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://d65ea401d5953938dfa9d7054c04314a9649809baf5dc76e40efbed7dcd4817d
    image: nginx:1.14-alpine
    imageID: docker-pullable://nginx@sha256:b67e90a1d8088f0e205c77c793c271524773a6de163fb3855b1c1bedf979da7d
    lastState: {}
    name: nginx-deploy
    ready: true
    restartCount: 0
    state:
      running:
        startedAt: "2019-04-06T11:29:51Z"
  hostIP: 192.168.31.22
  phase: Running
  podIP: 10.244.3.2
  qosClass: BestEffort
  startTime: "2019-04-06T11:29:30Z"



#######
apiVersion: v1                    #必选,版本号,例如v1,版本号必须可以用 kubectl api-versions 查询到 .
kind: Pod                     #必选,Pod
metadata:                     #必选,元数据
  name: string                    #必选,Pod名称
  namespace: string               #必选,Pod所属的命名空间,默认为"default"
  labels:                     #自定义标签
    - name: string                 #自定义标签名字
  annotations:                    #自定义注释列表
    - name: string
spec:                        #必选,Pod中容器的详细定义
  containers:                   #必选,Pod中容器列表
  - name: string                  #必选,容器名称,需符合RFC 1035规范
    image: string                 #必选,容器的镜像名称
    imagePullPolicy: [ Always|Never|IfNotPresent ]  #获取镜像的策略 Alawys表示下载镜像 IfnotPresent表示优先使用本地镜像,否则下载镜像,Nerver表示仅使用本地镜像
    command: [string]             #容器的启动命令列表,如不指定,使用打包时使用的启动命令
    args: [string]                #容器的启动命令参数列表
    workingDir: string              #容器的工作目录
    volumeMounts:               #挂载到容器内部的存储卷配置
    - name: string               #引用pod定义的共享存储卷的名称,需用volumes[]部分定义的的卷名
      mountPath: string             #存储卷在容器内mount的绝对路径,应少于512字符
      readOnly: boolean             #是否为只读模式
    ports:                    #需要暴露的端口库号列表
    - name: string               #端口的名称
      containerPort: int            #容器需要监听的端口号
      hostPort: int               #容器所在主机需要监听的端口号,默认与Container相同
      protocol: string              #端口协议,支持TCP和UDP,默认TCP
    env:                      #容器运行前需设置的环境变量列表
    - name: string                #环境变量名称
      value: string               #环境变量的值
    resources:                    #资源限制和请求的设置
      limits:                   #资源限制的设置
        cpu: string               #Cpu的限制,单位为core数,将用于docker run --cpu-shares参数
        memory: string              #内存限制,单位可以为Mib/Gib,将用于docker run --memory参数
      requests:                   #资源请求的设置
        cpu: string               #Cpu请求,容器启动的初始可用数量
        memory: string              #内存请求,容器启动的初始可用数量
    livenessProbe:                #对Pod内各容器健康检查的设置,当探测无响应几次后将自动重启该容器,检查方法有exec、httpGet和tcpSocket,对一个容器只需设置其中一种方法即可
      exec:                   #对Pod容器内检查方式设置为exec方式
        command: [string]           #exec方式需要制定的命令或脚本
      httpGet:                  #对Pod内个容器健康检查方法设置为HttpGet,需要制定Path、port
        path: string
        port: number
        host: string
        scheme: string
        HttpHeaders:
        - name: string
          value: string
      tcpSocket:              #对Pod内个容器健康检查方式设置为tcpSocket方式
         port: number
       initialDelaySeconds: 0       #容器启动完成后首次探测的时间,单位为秒
       timeoutSeconds: 0          #对容器健康检查探测等待响应的超时时间,单位秒,默认1秒
       periodSeconds: 0           #对容器监控检查的定期探测时间设置,单位秒,默认10秒一次
       successThreshold: 0
       failureThreshold: 0
       securityContext:
         privileged: false
    restartPolicy: [Always | Never | OnFailure] #Pod的重启策略,Always表示一旦不管以何种方式终止运行,kubelet都将重启,OnFailure表示只有Pod以非0退出码退出才重启,Nerver表示不再重启该Pod
    nodeSelector: obeject         #设置NodeSelector表示将该Pod调度到包含这个label的node上,以key:value的格式指定
    imagePullSecrets:           #Pull镜像时使用的secret名称,以key:secretkey格式指定
    - name: string
    hostNetwork: false            #是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络
    volumes:                  #在该pod上定义共享存储卷列表
    - name: string              #共享存储卷名称 (volumes类型有很多种)
      emptyDir: {}              #类型为emtyDir的存储卷,与Pod同生命周期的一个临时目录。为空值
      hostPath: string            #类型为hostPath的存储卷,表示挂载Pod所在宿主机的目录
        path: string              #Pod所在宿主机的目录,将被用于同期中mount的目录
      secret:                 #类型为secret的存储卷,挂载集群与定义的secre对象到容器内部
        scretname: string  
        items:     
        - key: string
          path: string
      configMap:                #类型为configMap的存储卷,挂载预定义的configMap对象到容器内部
        name: string
        items:
        - key: string
          path: string

 

posted @ 2022-11-14 23:39  Sky-wings  阅读(21)  评论(0编辑  收藏  举报