概述#

回顧前面的章節,操作 Kubernetes 不外乎兩件事:撰寫 YAML 設定檔,以及使用 kubectl 指令。kubectl 本質上就是把 kube-apiserver 的 RESTful API 包裝成易用的 CLI,熟悉它能讓我們更深入理解叢集行為,遇到問題時也能舉一反三、更靈活地除錯。

語法總覽#

kubectl 的指令語法為:

kubectl [command] [TYPE] [NAME] [flags]

四個欄位的角色如下:

  • command:要執行的動作,例如 creategetdescribedeleteapply
  • TYPE:資源類型,不分大小寫,可使用單數、複數或縮寫。例如 podpodspo
  • NAME:資源名稱,區分大小寫;省略時表示對該類型所有資源生效。
  • flags:額外旗標,例如 -s / --server 指定 API Server 位址。

命令列上的旗標會覆寫預設值與環境變數。需要說明時可以執行 kubectl help

多資源指定#

操作多個資源時可以混合使用以下寫法:

  • 同型多名:TYPE name1 name2 ...,例如 kubectl get pod example-pod1 example-pod2
  • 不同型分別指定:TYPE/name,例如 kubectl get pod/example-pod1 replicationcontroller/example-rc1
  • 透過檔案指定:-f file1 -f file2,例如 kubectl get -f ./pod.yaml

實務上偏好使用 YAML 而非 JSON,因為 YAML 對人比較友善。

常用指令#

apply:以檔案或標準輸入更新資源#

# 以 example-service.yaml 套用 / 更新資源
kubectl apply -f example-service.yaml

# 套用整個目錄底下的 yaml / yml / json
kubectl apply -f <directory>

describe:顯示資源詳細資訊#

kubectl describe nodes <node-name>
kubectl describe pods/<pod-name>
kubectl describe pods <rc-name>   # ReplicationController 管理的所有 Pod
kubectl describe pods             # 所有 Pod

get:列出叢集中的資源#

get 可以列出 Node、Pod、Deployment、Service 等任何資源。沒有指定 namespace 時,預設只看 default namespace。

kubectl get po -o wide               # 取得所有 Pod 詳細資訊
kubectl get po --all-namespaces      # 跨 namespace 列出所有 Pod
kubectl get po --show-labels         # 顯示 Label
kubectl get namespace                # 列出所有 namespace

同樣模式可以套用到其他資源,例如 kubectl get svckubectl get nodeskubectl get deploy

create:依檔案建立資源#

kubectl create -f demo-deployment.yaml
kubectl create -f demo-service.yaml

delete:刪除資源#

kubectl delete -f demo-deployment.yaml
kubectl delete -f demo-service.yaml
kubectl delete <resource-name>

run:直接從指令啟動容器#

# 語法
kubectl run NAME --image=image [--env="key=value"] \
    [--port=port] [--replicas=replicas] [--dry-run=bool] \
    [--overrides=inline-json] [--command] -- [COMMAND] [args...]

# 範例:跑 3 個副本、Label 為 app=example、暴露 80 port 的 nginx
kubectl run nginx --replicas=3 --labels="app=example" --image=nginx:1.10 --port=80

expose:用 Service 暴露現有資源#

# 替 nginx Deployment 建立一個對外的 NodePort Service
kubectl expose deployment nginx --port=88 --type=NodePort --target-port=80 --name=nginx-service

set:修改既有資源的特定欄位#

# 範例語法(亦可改 env、image、resources、selector、serviceaccount、subject)
kubectl set resources (-f FILENAME | TYPE NAME) ([--limits=LIMITS & --requests=REQUESTS])

exec:在 Pod 內的容器執行命令#

# 在 Pod 第一個容器執行 date
kubectl exec <pod-name> -- date

# 指定容器
kubectl exec <pod-name> -c <container-name> -- date

# 互動式 shell
kubectl exec -ti <pod-name> -- /bin/bash

logs:查看容器日誌#

kubectl logs <pod-name>      # 取得目前的日誌快照
kubectl logs -f <pod-name>   # 類似 tail -f 的串流模式

小結#

掌握 kubectl 等同於掌握與 Kubernetes 對話的語言。先記熟最常用的 applygetdescribedeletelogsexec,其他指令隨需要再查表,操作熟練後就能順著語法直覺地推測新指令的用法。

原文出處#

  • GitHub:https://github.com/MikeHsu0618/2022-ithelp/tree/main/Day11
  • iThome:https://ithelp.ithome.com.tw/articles/10289259