k8s基礎(chǔ)知識總結(jié)

k8s入門知識點

[TOC]

k8s并不神秘,你可以結(jié)合vm和redis之類的中間件

Q-1:為什么需要k8s

Q0:k8s架構(gòu),k8s基本概念入門

Q1:k8s的yml講解。

Q2:k8s能做什么?k8s如何做?

推薦官方文檔和中文文檔:

1.為什么需要k8s

來個官方鏈接:https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/

2.基本架構(gòu)和基本概念入門

2.1基本架構(gòu)

對比幾張來自不同網(wǎng)站的架構(gòu)圖

Kubernetes的組成

[圖片上傳失敗...(image-eb049d-1582014664031)]

必須包含master和node 各至少一個。

  • master節(jié)點可認為是管家,包含核心組件

    • <1>api-server(一組Restful的api接口,k8s集群控制的唯一入口和前端,是組件間交互的中樞,像是身份認證,授權(quán)等機制都由api提供)
    • <2>數(shù)據(jù)管理(k8s的數(shù)據(jù)均存儲在etcd中,僅由apiserver操作數(shù)據(jù))
    • <3>scheduler(pod調(diào)度,可自定義調(diào)度算法)
    • <4>controller-manager(管理集群內(nèi)各類資源controller,如副本數(shù),endpoint,namespace,自愈等,使之始終處于“期望狀態(tài)”)等功能。

    官方推薦master部署在獨立的物理主機上,該主機一般不會run其他服務(wù)。

  • node 節(jié)點就是用來run實際的pod,包含

    • kubelet(systemd來進行管理,定期向master 匯報node狀態(tài),并接受apiserver的命令,負責node和master之間的通信,可認為是node的聲明周期管理器)
    • kube-proxy(service的代理器,將到達service的request load到具體的endpoint去,由iptables mode實現(xiàn),比如常用的nodeport模式可實現(xiàn)外部訪問集群內(nèi)部service)
    • container - runtime (還包含了各種容器,如docker的運行環(huán)境)。
  • 如下單service的應(yīng)用外部訪問示意:hello service對外提供服務(wù),內(nèi)部負載了3個pod,controller 為deployment

image-20200206141241312

2.2 k8s的對象模型

k8s可以看做是面向?qū)ο蟮?,每類服?wù)可看做是k8s的一個對象。這些對象由用戶定義yaml,k8s的api負責創(chuàng)建。所有對象包含spec(規(guī)范)+status兩類基本信息。

例如:k8s創(chuàng)建pod的api為:https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#pod-v1-core

kubectl 也會將yaml轉(zhuǎn)成json發(fā)送到master節(jié)點。

image-20200206162500055

k8s中常用的對象有pod、deployment、service、statefulSet等,每個對象至少包含3個metadata:namespace、name、uid。

2.2.1 k8s中常見的object kind:
  • pod

    • 基本調(diào)度單元,特定關(guān)系的一組容器集合,最小的部署集合。
    • 非持久性實體,調(diào)度失敗、自愈等情況會被終止,重建,不建議手動創(chuàng)建Pod,而是通過controller創(chuàng)建pod,如deployment。
  • Service

    • pod 重啟之后ip會改變,多個相同服務(wù)的pod需要有discovery+loadbalance 。這一點與“微服務(wù)”中的概念一致。通過label selector 可輕松實現(xiàn)邏輯分組。
    • service 的聲明周期內(nèi),ip不會改變??赏ㄟ^nodeport 暴露到外部。
    • 有的service不需要ip、有的service 不需要負載均衡。
  • Controllers

    • Replicaset (rs)副本數(shù),用于loadbalance和冗余。(老版本是ReplicationController- rc,算是功能升級,官方推薦使用rs 代替rc)?,F(xiàn)階段非特殊情況如升級pod的操作,也不推薦單獨使用,

    • Deployment

      使用并管理rs ,算是更高一層的概念,這是現(xiàn)在比較常用的部署app的方式。deployment為pod和rs提供聲明式更新(而非命令式)。支持滾動更新(rollingUpdate),支持回滾操作。

img
  • statefulSet(k8s 1.9 GA)

    我們自己開發(fā)的應(yīng)用一般都是stateless的,像是redis、zk、kafka、mysql這類的中間件通常需要使用statefulSet。通常適用于穩(wěn)定的持久存儲、穩(wěn)定的網(wǎng)絡(luò)標識、有序部署有序擴展、有序收縮、有序滾動升級的場景。

    pod的存儲一般都是volumes外掛到persistent介質(zhì)。并且伸縮或刪除不會刪除關(guān)聯(lián)的存儲。需要headless service負責pod的網(wǎng)絡(luò)身份。

    <font color=red size=1> "注意:statefulSet 對應(yīng)的service為headless servie,和普通的service的區(qū)別在于,普通的有cluster ip,通過只有service 有dns,通過iptables進行負載。headless service無cluster ip,endpoints是所有pod的dns地址。就意味著statefulset 創(chuàng)建pod的時候為pod生成了dns信息。如3 節(jié)點的mysql,會生成mysql-0 ... mysql-2三個pod(pod名稱生產(chǎn)規(guī)則為pod+遞增序號),并且會生成域: $(podname).(headless server name),完整FQDN為: $(podname).(headless server name).namespace.svc.cluster.local" </font>

    看一個完整的statefulSet + headless service 的示例。

    apiVersion: v1
    kind: Service
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      ports:
      - port: 80
        name: web
      clusterIP: None
      selector:
        app: nginx
    ---
    apiVersion: apps/v1beta1
    kind: StatefulSet
    metadata:
      name: web
    spec:
      serviceName: "nginx"
      replicas: 1
      template:
        metadata:
          labels:
            app: nginx
        spec:
          containers:
          - name: nginx
            image: nginx:1.11
            ports:
            - containerPort: 80
              name: web
            volumeMounts:
            - name: www
              mountPath: /usr/share/nginx/html
          nodeSelector:
            node: kube-node3
          volumes:
            - name: www
              hostPath:
                path: /mydir
    
  • DeamonSet

    每個node都有一個pod副本運行。常用在后臺常駐程序如ceph,日志收集,心跳檢查,Prometheus exporter等。

  • ConfigMap

    向pod 提供非敏感的配置信息,支持鍵值對,單個屬性,配置文件。

    使用方式:環(huán)境變量,容器命令行參數(shù),數(shù)據(jù)卷掛載。

    定義示例:

    apiVersion:V1
    kind:ConfigMap
    metadata:
        name:hello-config
        namespace:public-config
    data:
        title:hello everybody
        sex:girl
    

    引用示例:

    apiVersion:V1
    kind:deployment
    metadata:
        name:hello-dem
    spec:
        containers:
        - name:goodboy
            image:hub/images
            command:["/bin/bash","-c","echo ${envTitle} ${envSex}"]
            env:
                - name:envTitle
                  valueFrom:
                    configMapKeyRef:
                        name:hello-config
                        key:title
                - name:envSex
            valueFrom:
                configMapKeyRef:
                    name:hello-config
                    key:sex
    
  • Secret

    對應(yīng)于ConfigMap,用于敏感信息配置,如token,密碼,秘鑰等。

  • Endpoints

    service 和 pod 之間的關(guān)系會創(chuàng)建endpoint對象,默認與service 同名。kube-proxy將會監(jiān)聽service 和 endpoint的變化,從而更新iptables的規(guī)則。

  • PodDisruptionBudget(pdb,主動驅(qū)逐保護)

    • 沒有pdb。當進行節(jié)點維護時,如果某個服務(wù)的多個pod在該節(jié)點上,則節(jié)點的停機可能會造成服務(wù)中斷或者服務(wù)降級。舉個例子,某服務(wù)有5個pod,最低3個pod能保證服務(wù)質(zhì)量,否則會造成響應(yīng)慢等影響,此時該服務(wù)的4個pod在node01上,如果對node01進行停機維護,此時只有1個pod能正常對外服務(wù),在node01的4個pod遷移過程中,就會影響該服務(wù)正常響應(yīng);
    • pdb能保證應(yīng)用在節(jié)點維護時不低于一定數(shù)量的pod運行,從而保持服務(wù)質(zhì)量;
  • 等等其他的如 ingress

2.2.2 k8s中有常見的metadata
  • name && UID (uid是在k8s的整個聲明周期中均唯一,不會產(chǎn)生相同的uid,可對等為mysql的auto increment key)

    來看一個api訪問對象的路徑:/api/{version}/namespaces/{namespace}/{object-kind}/{name} ,k8s通過層層限定來尋找唯一標識的name。

  • namespace

    對一組資源和對象的抽象集合,從邏輯上劃分k8s實現(xiàn)分層管理,并實現(xiàn)一定層度上的資源和權(quán)限隔離。

    內(nèi)置三個namespace:default,kube-system(存放api-server、dns插件等),kube-public(供所有用戶包含未經(jīng)過身份驗證的用戶使用,實現(xiàn)資源集群內(nèi)共享)

    Node和persistentVolume(簡稱PV,通過PVC和pod綁定)不屬于任何namespace。

  • label

    標識性的數(shù)據(jù),有嚴格的命名規(guī)范,k8s可通過標簽組合管理對象,達到松耦合。在spec中通過selectors進行匹配。

  • annotation(理解為java注釋吧)

    非標識性的元數(shù)據(jù)附加到對象上。通常會有時間戳,版本號,用戶信息等輔助信息。

2.2.3 k8s spec中常見的參數(shù)
  • selectors(標簽和標簽選擇器)

    對應(yīng)label對應(yīng)的key-value 進行對象的選擇

2.3 k8s的ip模型

k8s的ip:

  • node Ip :node節(jié)點的ip,為物理ip.
  • pod Ip:pod的ip,即docker 容器的ip,為虛擬ip。
  • cluster Ip:service 的ip,為虛擬ip。提供一個集群內(nèi)部的虛擬IP以供Pod訪問。

2.4 k8s的volume

k8s的volume和docker有所不同,v是獨立于容器的,與pod聲明周期相同,即pod刪除空間也被刪除。有多重類型

  • emptydir

    空目錄,pod中的容器會共享此目錄

    如下所示,busybox的文件寫入,在nginx容器中能夠讀出來。

    [root@master ~]# cat test.yaml 
    apiVersion: v1
    kind: Service
    metadata:
      name: serivce-mynginx
      namespace: default
    spec:
      type: NodePort
      selector:
        app: mynginx
      ports:
      - name: nginx
        port: 80
        targetPort: 80
        nodePort: 30080
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: deploy
      namespace: default
    spec:
      replicas: 1
      selector: 
        matchLabels:
          app: mynginx
      template:
        metadata:
          labels:
            app: mynginx
        spec:
          containers:
          - name: mynginx
            image: lizhaoqwe/nginx:v1
            volumeMounts:
            - mountPath: /usr/share/nginx/html/
              name: share
            ports:
            - name: nginx
              containerPort: 80
          - name: busybox
            image: busybox
            command:
            - "/bin/sh"
            - "-c"
            - "sleep 4444"
            volumeMounts:
            - mountPath: /data/
              name: share
          volumes:
          - name: share
            emptyDir: {}
    
  • hostpath

    使用node的目錄進行掛載

  • configmap && secret

    前面講過,configmap和secret 都可以使用文件的方式,也可以把文件直接掛載到容器中。

    如:

      spec:
          containers:
          - name: nginx
            image: nginx
            ports:
            - name: nginx
              containerPort: 80
            volumeMounts:
              - name: html-config
                mountPath: /nginx/vars/
                readOnly: true
     volumes:
          - name: html-config
            configMap:
              name: nginx-var
    

2.5 k8s port

Port,Targetport,Nodeport區(qū)別

service 暴露nodeport 到node上,node 接受request 之后通過kube-proxy 負載到具體的pod(iptables 或 ipvs)。

k8s端口

3.k8s yaml講解

一個yaml通常如下:其中apiVersion、kind、metadata、spec(規(guī)格)是必填的項目。通常spec對于對象而言是能起決定性作用的描述。且對于pod、deployment、service等對象有各自特殊格式的spec。

3.1 Depolyment的yaml示例

Deployment API 版本對照表

Kubernetes 版本 Deployment 版本
v1.5-v1.15 extensions/v1beta1
v1.7-v1.15 apps/v1beta1
v1.8-v1.15 apps/v1beta2
v1.9+ apps/v1

這是sre定義的內(nèi)容:

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  labels:
    k8s-app: chainaccesspipe   # lables k-v形式供service selector選擇
  name: chainaccesspipe
  namespace: chainaccess-dev  # 命名空間
    annotations:
        title: "這是個測試title"
        date: "2020/10/10 "
        status: "be happy"
        
spec:
  replicas: 1  # 副本數(shù)
  selector:
    matchLabels:
      k8s-app: chainaccesspipe  #template選擇器
  template:
    metadata:
      labels:
        k8s-app: chainaccesspipe
    spec:
      initContainers: #初始化容器
      - image: www.xxx.com/middleware/sysctl:latest
        imagePullPolicy: Always
        name: sysctl
        resources:
          limits:
            cpu: 20m
            memory: 20Mi
          requests:
            cpu: 20m
            memory: 20Mi
        securityContext:
          privileged: true
          runAsUser: 0
      containers:
      - name: chainaccesspipe
        image: www.xxx.com/baseserver-dev/pipe:integration.0.9.1.0.0
       # resources:
       #   requests:
       #     memory: "2G"
       #     cpu: "350m"
       #   limits:
       #     memory: "2G"
       #     cpu: 1
#        livenessProbe:
#          httpGet:
#            path: /actuator/health
#            port: 8017
#          initialDelaySeconds: 150
#          periodSeconds: 5
#        readinessProbe:
#          httpGet:
#            path: /actuator/health
#            port: 8017
#          initialDelaySeconds: 150
#          periodSeconds: 3
        env: # 環(huán)境變量
        - name: LC_ALL
          value: en_US.utf8
        - name: JAVA_OPTS_OVERRIDE
          value: |-
            -Xms1024m
            -Xmx1024m
            -Dport=8017
            -Dnacos-namespace=5ea6a570-379f-4d74-9553-066a2227720f
            -Duser.timezone=GMT+08
        args:
        - -jar
        - /app/app.jar
        ports:
        - containerPort: 8017  #容器暴露端口
        imagePullPolicy: Always
      securityContext:
        runAsUser: 1000
        fsGroup: 1000
      imagePullSecrets:
      - name: sec8084
---
apiVersion: v1
kind: Service
metadata:
  labels:
    k8s-app: chainaccesspipe
  annotations:
    prometheus.io/scrape: "true"
    prometheus.io/app-metrics-path: /actuator/prometheus
  name: chainaccesspipe
  namespace: chainaccess-dev
spec:
  ports:
    - port: 8017
      targetPort: 8017
      nodePort: 28017
  type: NodePort
  selector:
    k8s-app: chainaccesspipe

接下來我們登陸21 ,通過api獲取下完整的map:

curl -s 127.0.0.1:8080/apis/apps/v1/namespaces/chainaccess-dev/deployments/chainaccesspipe  | jq 

內(nèi)容如下,這個是v1版本下,完整的map,我們可以對比下定義的yaml。

{
  "kind": "Deployment",
  "apiVersion": "apps/v1",
  "metadata": {
    "name": "chainaccesspipe",
    "namespace": "chainaccess-dev",
    "selfLink": "/apis/apps/v1/namespaces/chainaccess-dev/deployments/chainaccesspipe",
    "uid": "9ca01515-2aca-11ea-b7ca-005056aa5684",
    "resourceVersion": "84030034",
    "generation": 1,
    "creationTimestamp": "2019-12-30T06:07:08Z",
    "labels": {
      "k8s-app": "chainaccesspipe"
    },
    "annotations": {
      "deployment.kubernetes.io/revision": "1"
    }
  },
  "spec": {
    "replicas": 1,
    "selector": {
      "matchLabels": {
        "k8s-app": "chainaccesspipe"
      }
    },
    "template": {
      "metadata": {
        "creationTimestamp": null,
        "labels": {
          "k8s-app": "chainaccesspipe"
        }
      },
      "spec": {
        "initContainers": [
          {
            "name": "sysctl",
            "image": "harbor.xxx.com/middleware/sysctl:latest",
            "resources": {
              "limits": {
                "cpu": "20m",
                "memory": "20Mi"
              },
              "requests": {
                "cpu": "20m",
                "memory": "20Mi"
              }
            },
            "terminationMessagePath": "/dev/termination-log",
            "terminationMessagePolicy": "File",
            "imagePullPolicy": "Always",
            "securityContext": {
              "privileged": true,
              "runAsUser": 0
            }
          }
        ],
        "containers": [
          {
            "name": "chainaccesspipe",
            "image": "harbor.xxx.com/baseserver-dev/pipe:release.0.9.1.1.0",
            "args": [
              "-jar",
              "/app/app.jar"
            ],
            "ports": [
              {
                "containerPort": 8080,
                "protocol": "TCP"
              }
            ],
            "env": [
              {
                "name": "LC_ALL",
                "value": "en_US.utf8"
              },
              {
                "name": "JAVA_OPTS_OVERRIDE",
                "value": "-Xms1024m\n-Xmx1024m\n-Dport=8080\n-Dnacos-server-addr=nacos-headless.nacos-server:8848\n-Dnacos-namespace=9482afb2-3267-45ea-92cd-48edaae5837b\n-Duser.timezone=GMT+08"
              }
            ],
            "resources": {},
            "terminationMessagePath": "/dev/termination-log",
            "terminationMessagePolicy": "File",
            "imagePullPolicy": "Always"
          }
        ],
        "restartPolicy": "Always",
        "terminationGracePeriodSeconds": 30,
        "dnsPolicy": "ClusterFirst",
        "securityContext": {
          "runAsUser": 1000,
          "fsGroup": 1000
        },
        "imagePullSecrets": [
          {
            "name": "sec8084"
          }
        ],
        "schedulerName": "default-scheduler"
      }
    },
    "strategy": {
      "type": "RollingUpdate",
      "rollingUpdate": {
        "maxUnavailable": "25%",
        "maxSurge": "25%"
      }
    },
    "revisionHistoryLimit": 10,
    "progressDeadlineSeconds": 600
  },
  "status": {
    "observedGeneration": 1,
    "replicas": 1,
    "updatedReplicas": 1,
    "readyReplicas": 1,
    "availableReplicas": 1,
    "conditions": [
      {
        "type": "Progressing",
        "status": "True",
        "lastUpdateTime": "2019-12-30T06:07:17Z",
        "lastTransitionTime": "2019-12-30T06:07:08Z",
        "reason": "NewReplicaSetAvailable",
        "message": "ReplicaSet \"chainaccesspipe-6bf9469bf4\" has successfully progressed."
      },
      {
        "type": "Available",
        "status": "True",
        "lastUpdateTime": "2020-01-19T08:10:00Z",
        "lastTransitionTime": "2020-01-19T08:10:00Z",
        "reason": "MinimumReplicasAvailable",
        "message": "Deployment has minimum availability."
      }
    ]
  }
}

3.2 pod完整yaml

apiVersion: v1                    #必選,版本號,例如v1,版本號必須可以用 kubectl api-versions 查詢到 .
kind: Pod                      #必選,Pod
metadata:                      #必選,元數(shù)據(jù)
  name: string                    #必選,Pod名稱
  namespace: string               #必選,Pod所屬的命名空間,默認為"default"
  labels:                       #自定義標簽
    - name: string                 #自定義標簽名字
  annotations:                           #自定義注釋列表
    - name: string
spec:                            #必選,Pod中容器的詳細定義
  containers:                       #必選,Pod中容器列表
  - name: string                        #必選,容器名稱,需符合RFC 1035規(guī)范
    image: string                       #必選,容器的鏡像名稱
    imagePullPolicy: [ Always|Never|IfNotPresent ]  #獲取鏡像的策略 Alawys表示下載鏡像 IfnotPresent表示優(yōu)先使用本地鏡像,否則下載鏡像,Nerver表示僅使用本地鏡像
    command: [string]               #容器的啟動命令列表,如不指定,使用打包時使用的啟動命令
    args: [string]                     #容器的啟動命令參數(shù)列表
    workingDir: string                     #容器的工作目錄
    volumeMounts:                 #掛載到容器內(nèi)部的存儲卷配置
    - name: string                 #引用pod定義的共享存儲卷的名稱,需用volumes[]部分定義的的卷名
      mountPath: string                 #存儲卷在容器內(nèi)mount的絕對路徑,應(yīng)少于512字符
      readOnly: boolean                 #是否為只讀模式
    ports:                      #需要暴露的端口庫號列表
    - name: string                 #端口的名稱
      containerPort: int                #容器需要監(jiān)聽的端口號
      hostPort: int                    #容器所在主機需要監(jiān)聽的端口號,默認與Container相同
      protocol: string                  #端口協(xié)議,支持TCP和UDP,默認TCP
    env:                          #容器運行前需設(shè)置的環(huán)境變量列表
    - name: string                    #環(huán)境變量名稱
      value: string                   #環(huán)境變量的值
    resources:                          #資源限制和請求的設(shè)置
      limits:                       #資源限制的設(shè)置
        cpu: string                   #Cpu的限制,單位為core數(shù),將用于docker run --cpu-shares參數(shù)
        memory: string                  #內(nèi)存限制,單位可以為Mib/Gib,將用于docker run --memory參數(shù)
      requests:                         #資源請求的設(shè)置
        cpu: string                   #Cpu請求,容器啟動的初始可用數(shù)量
        memory: string                    #內(nèi)存請求,容器啟動的初始可用數(shù)量
    livenessProbe:                    #對Pod內(nèi)各容器健康檢查的設(shè)置,當探測無響應(yīng)幾次后將自動重啟該容器,檢查方法有exec、httpGet和tcpSocket,對一個容器只需設(shè)置其中一種方法即可
      exec:                     #對Pod容器內(nèi)檢查方式設(shè)置為exec方式
        command: [string]               #exec方式需要制定的命令或腳本
      httpGet:                    #對Pod內(nèi)個容器健康檢查方法設(shè)置為HttpGet,需要制定Path、port
        path: string
        port: number
        host: string
        scheme: string
        HttpHeaders:
        - name: string
          value: string
      tcpSocket:            #對Pod內(nèi)個容器健康檢查方式設(shè)置為tcpSocket方式
         port: number
       initialDelaySeconds: 0       #容器啟動完成后首次探測的時間,單位為秒
       timeoutSeconds: 0          #對容器健康檢查探測等待響應(yīng)的超時時間,單位秒,默認1秒
       periodSeconds: 0           #對容器監(jiān)控檢查的定期探測時間設(shè)置,單位秒,默認10秒一次
       successThreshold: 0
       failureThreshold: 0
       securityContext:
         privileged: false
    restartPolicy: [Always | Never | OnFailure] #Pod的重啟策略,Always表示一旦不管以何種方式終止運行,kubelet都將重啟,OnFailure表示只有Pod以非0退出碼退出才重啟,Nerver表示不再重啟該Pod
    nodeSelector: obeject         #設(shè)置NodeSelector表示將該Pod調(diào)度到包含這個label的node上,以key:value的格式指定
    imagePullSecrets:         #Pull鏡像時使用的secret名稱,以key:secretkey格式指定
    - name: string
    hostNetwork: false            #是否使用主機網(wǎng)絡(luò)模式,默認為false,如果設(shè)置為true,表示使用宿主機網(wǎng)絡(luò)
    volumes:                  #在該pod上定義共享存儲卷列表
    - name: string              #共享存儲卷名稱 (volumes類型有很多種)
      emptyDir: {}              #類型為emtyDir的存儲卷,與Pod同生命周期的一個臨時目錄。為空值
      hostPath: string            #類型為hostPath的存儲卷,表示掛載Pod所在宿主機的目錄
        path: string                #Pod所在宿主機的目錄,將被用于同期中mount的目錄
      secret:                 #類型為secret的存儲卷,掛載集群與定義的secre對象到容器內(nèi)部
        scretname: string  
        items:     
        - key: string
          path: string
      configMap:                      #類型為configMap的存儲卷,掛載預定義的configMap對象到容器內(nèi)部
        name: string
        items:
        - key: string
          path: string

附錄:

附錄1:k8s常見api操作

# 查看當前集群支持的API版本
$ curl -s 127.0.0.1:8080/api/ | jq -r .versions

# 查看指定API的資源操作類型 返回一個字典列表
$ curl -s 127.0.0.1:8080/api/v1/ | jq keys
[
  "groupVersion",
  "kind",
  "resources"
]

# 查看當前k8s集群支持的操作類型
curl -s 127.0.0.1:8080/api/v1/ | jq .resources | grep "name\b"
    "name": "bindings",
    "name": "componentstatuses",
    "name": "configmaps",
    "name": "endpoints",
    "name": "events",
    "name": "limitranges",
    "name": "namespaces",
    "name": "namespaces/finalize",
    "name": "namespaces/status",
    "name": "nodes",
    "name": "nodes/proxy",
    "name": "nodes/status",
    "name": "persistentvolumeclaims",
    "name": "persistentvolumeclaims/status",
    "name": "persistentvolumes",
    "name": "persistentvolumes/status",
    "name": "pods",
    "name": "pods/attach",
    "name": "pods/binding",
    "name": "pods/eviction",
    "name": "pods/exec",
    "name": "pods/log",
    "name": "pods/portforward",
    "name": "pods/proxy",
    "name": "pods/status",
    "name": "podtemplates",
    "name": "replicationcontrollers",
    "name": "replicationcontrollers/scale",
    "name": "replicationcontrollers/status",
    "name": "resourcequotas",
    "name": "resourcequotas/status",
    "name": "secrets",
    "name": "serviceaccounts",
    "name": "services",
    "name": "services/proxy",
    "name": "services/status",

# 常用的,需要關(guān)注的幾個資源類型 【namespaces|nodes|pods|podtemplates|replicationcontrollers|services|secrets】

# 查看某個namespace的URL
$ curl -s 127.0.0.1:8080/api/v1/namespaces/ | jq .items | jq values[0]  | grep -E '(name|selfLink)'
    "name": "default",
    "selfLink": "/api/v1/namespaces/default",

# 查看namespace詳情
$ curl -s 127.0.0.1:8080/api/v1/namespaces/default | jq .spec
{
  "finalizers": [
    "kubernetes"
  ]
}




# 查看全部node
$ curl -s 127.0.0.1:8080/api/v1/nodes | jq .items | grep -E "\bname\b|selfLink"
      "name": "172.25.47.138",
      "selfLink": "/api/v1/nodes/172.25.47.138",
      "name": "172.25.47.202",
      "selfLink": "/api/v1/nodes/172.25.47.202",
      "name": "172.25.47.75",
      "selfLink": "/api/v1/nodes/172.25.47.75",
      "name": "10.0.0.121",
      "selfLink": "/api/v1/nodes/10.0.0.121",
      "name": "10.0.0.122",
      "selfLink": "/api/v1/nodes/10.0.0.122",

# 查看某個node詳情【當前該節(jié)點的資源信息以及設(shè)置限制條件,當前節(jié)點運行的pod容器以及鏡像相關(guān)信息】
$ curl -s 127.0.0.1:8080/api/v1/nodes/10.0.0.122 | jq .status
{
  "capacity": {
    "cpu": "4",
    "ephemeral-storage": "14987616Ki",
    "hugepages-2Mi": "0",
    "memory": "6627524Ki",
    "pods": "110"
  },
  "allocatable": {
    "cpu": "4",
    "ephemeral-storage": "13812586883",
    "hugepages-2Mi": "0",
    "memory": "6525124Ki",
    "pods": "110"
  },
  "conditions": [
    {
      "type": "OutOfDisk",
      "status": "False",
      "lastHeartbeatTime": "2018-07-19T03:15:50Z",
      "lastTransitionTime": "2018-06-28T01:59:06Z",
      "reason": "KubeletHasSufficientDisk",
      "message": "kubelet has sufficient disk space available"
    },
    {
      "type": "MemoryPressure",
      "status": "False",
      "lastHeartbeatTime": "2018-07-19T03:15:50Z",
      "lastTransitionTime": "2018-06-28T01:59:06Z",
      "reason": "KubeletHasSufficientMemory",
      "message": "kubelet has sufficient memory available"
    },
    {
      "type": "DiskPressure",
      "status": "False",
      "lastHeartbeatTime": "2018-07-19T03:15:50Z",
      "lastTransitionTime": "2018-06-28T01:59:06Z",
      "reason": "KubeletHasNoDiskPressure",
      "message": "kubelet has no disk pressure"
    },
    {
      "type": "PIDPressure",
      "status": "False",
      "lastHeartbeatTime": "2018-07-19T03:15:50Z",
      "lastTransitionTime": "2018-06-28T01:59:06Z",
      "reason": "KubeletHasSufficientPID",
      "message": "kubelet has sufficient PID available"
    },
    {
      "type": "Ready",
      "status": "True",
      "lastHeartbeatTime": "2018-07-19T03:15:50Z",
      "lastTransitionTime": "2018-07-18T08:18:31Z",
      "reason": "KubeletReady",
      "message": "kubelet is posting ready status"
    }
  ],
  "addresses": [
    {
      "type": "InternalIP",
      "address": "10.0.0.122"
    },
    {
      "type": "Hostname",
      "address": "10.0.0.122"
    }
  ],
  "daemonEndpoints": {
    "kubeletEndpoint": {
      "Port": 10250
    }
  },
  "nodeInfo": {
    "machineID": "cd7f16da1665b7cee74f46122e2d7cdd",
    "systemUUID": "0E96FBAF-C214-18F8-D9E6-8B65B9B5A413",
    "bootID": "f67f0185-4be6-41d0-b5e0-d126165f6986",
    "kernelVersion": "3.10.0-327.el7.x86_64",
    "osImage": "CentOS Linux 7 (Core)",
    "containerRuntimeVersion": "docker://1.12.6",
    "kubeletVersion": "v1.10.4",
    "kubeProxyVersion": "v1.10.4",
    "operatingSystem": "linux",
    "architecture": "amd64"
  },
  "images": [
    {
      "names": [
        "dockerhub.jd.com/wolf/fe-wolf@sha256:0b155e99f27de990cfd3a5f96bcc13b820530cf1236b96ca5d87efae4f65f62a",
        "dockerhub.jd.com/wolf/fe-wolf:latest"
      ],
      "sizeBytes": 352597644
    },
    {
      "names": [
        "xxbandy123/go-web@sha256:c375b479a74b0ec77608a221a28ddc4589149d55a04845eac697903add557c30",
        "xxbandy123/go-web:latest"
      ],
      "sizeBytes": 338268706
    },
    {
      "names": [
        "dockerhub.jd.com/gcr_mirror/pause-amd64@sha256:fcaff905397ba63fd376d0c3019f1f1cb6e7506131389edbcb3d22719f1ae54d",
        "dockerhub.jd.com/gcr_mirror/pause-amd64:3.1"
      ],
      "sizeBytes": 742472
    }
  ]
}


# 查看pod相關(guān)信息【由于一般k8s是不建議使用pod類型來直接控制容器的,因此這個接口直接查沒什么意義】

# 查看apis group相關(guān)信息
curl -s 127.0.0.1:8080/apis/extensions/v1beta1 | grep "\bname\b"
      "name": "daemonsets",
      "name": "daemonsets/status",
      "name": "deployments",
      "name": "deployments/rollback",
      "name": "deployments/scale",
      "name": "deployments/status",
      "name": "ingresses",
      "name": "ingresses/status",
      "name": "networkpolicies",
      "name": "podsecuritypolicies",
      "name": "replicasets",
      "name": "replicasets/scale",
      "name": "replicasets/status",
      "name": "replicationcontrollers",
      "name": "replicationcontrollers/scale",
$ curl -s 127.0.0.1:8080/apis/apps/v1beta1 | grep "\bname\b"
      "name": "controllerrevisions",
      "name": "deployments",
      "name": "deployments/rollback",
      "name": "deployments/scale",
      "name": "deployments/status",
      "name": "statefulsets",
      "name": "statefulsets/scale",
      "name": "statefulsets/status",





# 查看控制器對應(yīng)的控制器信息【statefulset,deployment】 這些控制器的信息一般在/apis/apps/下
# job和cronjob一般會在/apis/batch/下
$ curl -s 127.0.0.1:8080/apis/batch/v1 | grep "\bname\b"
      "name": "jobs",
      "name": "jobs/status",

curl -s 127.0.0.1:8080/apis/batch/v1/jobs | jq -r .items | grep name
      "name": "image-build-service",
      "namespace": "default",
      "selfLink": "/apis/batch/v1/namespaces/default/jobs/image-build-service",
        "job-name": "image-build-service"
          "name": "image-build-service",
            "job-name": "image-build-service"
              "name": "hosts",
              "name": "image-build-service",
                  "name": "dockerhost",
                  "name": "branch",
                  "name": "giturl",
                  "name": "app",
                  "name": "dockerfiledir",
                  "name": "hosts",



# 查看當前/apis/apps/支持的apiversion
$ curl -s 127.0.0.1:8080/apis/apps | jq .versions |grep "groupVersion"
    "groupVersion": "apps/v1",
    "groupVersion": "apps/v1beta2",
    "groupVersion": "apps/v1beta1",

# 查看應(yīng)用的api支持的相關(guān)資源類型 【daemonsets|deployments|replicasets|statefulsets】
$ curl -s 127.0.0.1:8080/apis/apps/v1 | jq .resources | grep "name\b"
    "name": "controllerrevisions",
    "name": "daemonsets",
    "name": "daemonsets/status",
    "name": "deployments",
    "name": "deployments/scale",
    "name": "deployments/status",
    "name": "replicasets",
    "name": "replicasets/scale",
    "name": "replicasets/status",
    "name": "statefulsets",
    "name": "statefulsets/scale",
    "name": "statefulsets/status",

# 問題:job類型的資源在哪里查看 batch/extension?

# 查看deployment名稱和selflink
$ curl -s 127.0.0.1:8080/apis/apps/v1/deployments | jq .items | grep   -E "(\bname\b|\bnamespace\b|selfLink)"
      "name": "test-go-web",
      "namespace": "default",
      "selfLink": "/apis/apps/v1/namespaces/default/deployments/test-go-web",

# 查看某個deployment詳情
$ kubectl get deployments -o wide
NAME          DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE       CONTAINERS    IMAGES                         SELECTOR
test-go-web   5         5         5            5           1h        test-go-web   xxbandy123/go-web   run=test-go-web
$ curl -s 127.0.0.1:8080/apis/apps/v1/namespaces/default/deployments/test-go-web  | jq .spec
{
  "replicas": 5,
  "selector": {
    "matchLabels": {
      "run": "test-go-web"
    }
  },
  "template": {
    "metadata": {
      "creationTimestamp": null,
      "labels": {
        "run": "test-go-web"
      }
    },
    "spec": {
      "containers": [
        {
          "name": "test-go-web",
          "image": "xxbandy123/go-web",
          "ports": [
            {
              "containerPort": 9090,
              "protocol": "TCP"
            }
          ],
          "resources": {},
          "terminationMessagePath": "/dev/termination-log",
          "terminationMessagePolicy": "File",
          "imagePullPolicy": "Always"
        }
      ],
      "restartPolicy": "Always",
      "terminationGracePeriodSeconds": 30,
      "dnsPolicy": "ClusterFirst",
      "securityContext": {},
      "schedulerName": "default-scheduler"
    }
  },
  "strategy": {
    "type": "RollingUpdate",
    "rollingUpdate": {
      "maxUnavailable": 1,
      "maxSurge": 1
    }
  },
  "revisionHistoryLimit": 10,
  "progressDeadlineSeconds": 600
}




# 查看service資源下的實例
# curl -s 127.0.0.1:8080/api/v1/services/ | jq ".items" | jq values[1] |grep -E "(\bname\b|selfLink|\bnamespace\b)"
    "name": "test-go-web",
    "namespace": "default",
    "selfLink": "/api/v1/namespaces/default/services/test-go-web",

# 查看某個service詳情 【具體的資源類型會被劃分到namespaces下】
$ curl -s 127.0.0.1:8080/api/v1/namespaces/default/services/test-go-web | jq -r '.spec'
{
  "ports": [
    {
      "protocol": "TCP",
      "port": 9090,
      "targetPort": 9090,
      "nodePort": 30315
    }
  ],
  "selector": {
    "run": "test-go-web"
  },
  "clusterIP": "10.254.141.49",
  "type": "NodePort",
  "sessionAffinity": "None",
  "externalTrafficPolicy": "Cluster"
}


# 查看configmap
$ curl -s 127.0.0.1:8080/api/v1/configmaps | jq .items

# 查看secrets
$ curl -s 127.0.0.1:8080/api/v1/secrets | jq .items | grep "\"\bname\b"



附錄2:參考資料:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容