iT邦幫忙

2024 iThome 鐵人賽

DAY 5
1
Kubernetes

都什麼年代了,還在學 Kubernetes系列 第 5

學 Kubernetes 的第五天 - Kubernetes 瑞士刀 - kubectl

  • 分享至 

  • xImage
  •  

在正式使用 Kubernetes 之前,還有一道最後的關卡:如何與叢集進行溝通。這個問題的答案就是 kubectl

什麼是 kubectl

在 Kubernetes 環境中,kubectl 是管理和操作叢集的主要工具,其原理是使用 Kubernetes API 與 Kubernetes 叢集的控制面板(Control panel)進行互動。

簡單來說,kubectl 是 Kubernetes 的命令行工具(CLI)。

安裝 kubectl

  • Ubuntu 可以直接透過 apt 倉庫安裝 kubectl
sudo apt-get update
sudo apt-get install -y kubectl
  • 檢查 kubectl 版本
kubectl version
---
Client Version: v1.29.2
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
Server Version: v1.30.0
  • 查看叢集資訊
kubectl cluster-info
---
Kubernetes control plane is running at https://127.0.0.1:39777
CoreDNS is running at https://127.0.0.1:39777/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

kubectl 使用 kubeconfig 檔案來尋找選擇叢集所需的資訊,該檔案包含了 Cluster、User 、Namespace、 authentication 、Context 等資訊。預設情況下 kubeconfig 檔案就是位於 $HOME/.kube 目錄下的 config 檔案。

由於我們在上一章已經使用 kind 建立叢集,kind 會自動建立 kubeconig 並添加必要的資訊。

  • 查看 kubeconig 檔案
cat ~/.kube/config

結果如下

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://127.0.0.1:39777
  name: kind-wslkind
contexts:
- context:
    cluster: kind-wslkind
    user: kind-wslkind
  name: kind-wslkind
current-context: kind-wslkind
kind: Config
preferences: {}
users:
- name: kind-wslkind
  user:
    client-certificate-data: DATA+OMITTED
    client-key-data: DATA+OMITTED

自動補全 & 別名

我們可以為 kubectl 設置別名和自動補全,簡化操作的複查度。

# 在 bash 中設定當前 shell 的自動補全,要先安裝 bash-completion 包
source <(kubectl completion bash) 
# 在你的 bash shell 中永久地新增自動補全
echo "source <(kubectl completion bash)" >> ~/.bashrc 
# 為 `kubectl` 命令設定別名
alias k=kubectl
# 將 `kubectl` 命令的自動補全功能應用到 `k` 命令上
complete -o default -F __start_kubectl k

完成上面的設置後,我們就可以達成以下的操作:

  • 使用 k 來取代 kubectl
k cluster-info
# 等價於
kubectl cluster-info
  • 指令輸入到一半,補全剩下的內容
kubectl clus
# -> 按下 tab 鍵
kubectl cluster-info

常用指令

接下來,我們將列舉一些常用的 kubectl 指令及標記(flags)清單。無需完全記住這些用法,只需大致瀏覽一遍,對其有個基本的印象即可。當你在後續的實作中遇到困難時,可以隨時回到這一章節進行查詢。

提醒

  • 我們經常用到 --all-namespaces 參數,你應該要知道它的簡寫:kubectl -A
  • 常用的 K8s 資源大多都有短別名,比如 pods 也可以寫作 podpo。想要查看資源的短別名,可以使用指令 kubectl api-resources 找到資源對應的 SHORTNAMES 欄位

context 和 configuration

設定 kubectl 與哪個 Kubernetes 叢集進行通訊和修改組態資訊

kubectl config view # 顯示合併的 kubeconfig 組態

# 同時使用多個 kubeconfig 檔案並查看合併的組態
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2

kubectl config view

# 顯示合併的 kubeconfig 組態和原始證書資料以及公開的 Secret
kubectl config view --raw

# 獲取 e2e 使用者的密碼
kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'

# 獲取 e2e 使用者的證書
kubectl config view --raw -o jsonpath='{.users[?(.name == "e2e")].user.client-certificate-data}' | base64 -d

kubectl config view -o jsonpath='{.users[].name}'    # 顯示第一個使用者
kubectl config view -o jsonpath='{.users[*].name}'   # 獲取使用者列表
kubectl config get-contexts                          # 顯示上下文列表
kubectl config get-contexts -o name                  # 獲取所有上下文的名稱
kubectl config current-context                       # 展示當前所處的上下文
kubectl config use-context my-cluster-name           # 設定默認的上下文為 my-cluster-name

kubectl config set-cluster my-cluster-name           # 在 kubeconfig 中設定叢集條目

# 在 kubeconfig 中組態代理伺服器的 URL,以用於該客戶端的請求
kubectl config set-cluster my-cluster-name --proxy-url=my-proxy-url

# 新增新的使用者組態到 kubeconf 中,使用 basic auth 進行身份認證
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword

# 在指定上下文中持久性地保存名字空間,供所有後續 kubectl 命令使用
kubectl config set-context --current --namespace=ggckad-s2

# 使用特定的使用者名稱和名字空間設定上下文
kubectl config set-context gce --user=cluster-admin --namespace=foo \
  && kubectl config use-context gce

kubectl config unset users.foo                       # 刪除使用者 foo

# 設定或顯示 context / namespace 的短別名
# (僅適用於 bash 和 bash 相容的 shell,在使用 kn 設定命名空間之前要先設定 current-context)
alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ; } ; f'
alias kn='f() { [ "$1" ] && kubectl config set-context --current --namespace $1 || kubectl config view --minify | grep namespace | cut -d" " -f6 ; } ; f'

kubectl apply

通過執行 kubectl apply 可以在 Kubernetes 集群中創建和更新資源。這是管理生產環境中 Kubernetes 應用的推薦方法。

kubectl apply -f ./my-manifest.yaml                  # 建立資源
kubectl apply -f ./my1.yaml -f ./my2.yaml            # 使用多個檔案建立
kubectl apply -f ./dir                               # 基於目錄下的所有清單檔案建立資源
kubectl apply -f https://example.com/manifest.yaml   # 從 URL 中建立資源(注意:這是一個示例域名,不包含有效的清單)
kubectl create deployment nginx --image=nginx        # 啟動單實例 nginx

# 建立一個列印 “Hello World” 的 Job
kubectl create job hello --image=busybox:1.28 -- echo "Hello World" 

# 建立一個列印 “Hello World” 間隔 1 分鐘的 CronJob
kubectl create cronjob hello --image=busybox:1.28   --schedule="*/1 * * * *" -- echo "Hello World"    

kubectl explain pods                          # 獲取 Pod 清單的文件說明

# 從標準輸入建立多個 YAML 對象
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: busybox-sleep
spec:
  containers:
  - name: busybox
    image: busybox:1.28
    args:
    - sleep
    - "1000000"
---
apiVersion: v1
kind: Pod
metadata:
  name: busybox-sleep-less
spec:
  containers:
  - name: busybox
    image: busybox:1.28
    args:
    - sleep
    - "1000"
EOF

# 建立有多個 key 的 Secret
kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  password: $(echo -n "s33msi4" | base64 -w0)
  username: $(echo -n "jane" | base64 -w0)
EOF

說明:

什麼是組態檔案

Kubernetes 組態檔案(清單檔案) 用來描述叢集中的資源配置,通常使用 YAML 或 JSON 格式編寫。這些檔案是管理和部署 Kubernetes 資源的核心工具。

kubectl apply 指令可將組態檔案應用到 Kubernetes 叢集中,負責建立或更新資源。相比之下,雖然 kubectl create 也能用來建立資源,但它的靈活性較低,無法處理複雜的配置。

建立資源時,可以在指令後面加上 --dry-run -o yaml 參數,這會輸出資源的組態檔案格式,而不會執行創建操作。

kubectl run pod my-pod --image=nginx --dry-run=client -o yaml
# 將組態檔案格式保存到文件
kubectl run pod my-pod --image=nginx --dry-run=client -o yaml > my-pod.yaml

查看資源時,可以在指令中加上 -o yaml ,來輸出該資源的組態檔案。

kubectl get pod my-pod -o yaml

查看和尋找資源

# get 命令的基本輸出
kubectl get services                          # 列出當前命名空間下的所有 Service
kubectl get pods --all-namespaces             # 列出所有命名空間下的全部的 Pod
kubectl get pods -o wide                      # 列出當前命名空間下的全部 Pod 並顯示更詳細的資訊
kubectl get deployment my-dep                 # 列出某個特定的 Deployment
kubectl get pods                              # 列出當前命名空間下的全部 Pod
kubectl get pod my-pod -o yaml                # 獲取一個 Pod 的 YAML

# describe 命令的詳細輸出
kubectl describe nodes my-node
kubectl describe pods my-pod

# 列出當前名字空間下所有 Service,按名稱排序
kubectl get services --sort-by=.metadata.name

# 列出 Pod,按重啟次數排序
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

# 列舉所有 PV 持久卷,按容量排序
kubectl get pv --sort-by=.spec.capacity.storage

# 獲取包含 app=cassandra 標籤的所有 Pod 的 version 標籤
kubectl get pods --selector=app=cassandra -o \
  jsonpath='{.items[*].metadata.labels.version}'

# 檢索帶有 “.” 鍵值,例如 'ca.crt'
kubectl get configmap myconfig \
  -o jsonpath='{.data.ca\.crt}'

# 檢索一個 base64 編碼的值,其中的鍵名應該包含減號而不是下劃線
kubectl get secret my-secret --template='{{index .data "key-name-with-dashes"}}'

# 獲取所有工作節點(使用選擇算符以排除標籤名稱為 'node-role.kubernetes.io/control-plane' 的結果)
kubectl get node --selector='!node-role.kubernetes.io/control-plane'

# 獲取當前命名空間中正在運行的 Pod
kubectl get pods --field-selector=status.phase=Running

# 獲取全部節點的 ExternalIP 地址
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'

# 列出屬於某個特定 RC 的 Pod 的名稱
# 在轉換對於 jsonpath 過於複雜的場合,"jq" 命令很有用;可以在 https://jqlang.github.io/jq/ 找到它
sel=${$(kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?}
echo $(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name})

# 顯示所有 Pod 的標籤(或任何其他支援標籤的 Kubernetes 對象)
kubectl get pods --show-labels

# 檢查哪些節點處於就緒狀態
JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
 && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"
 
# 使用自訂列檢查哪些節點處於就緒狀態
kubectl get node -o custom-columns='NODE_NAME:.metadata.name,STATUS:.status.conditions[?(@.type=="Ready")].status'

# 不使用外部工具來輸出解碼後的 Secret
kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{"### "}}{{$k}}{{"\n"}}{{$v|base64decode}}{{"\n\n"}}{{end}}'

# 列出被一個 Pod 使用的全部 Secret
kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq

# 列舉所有 Pod 中初始化容器的容器 ID(containerID)
# 可用於在清理已停止的容器時避免刪除初始化容器
kubectl get pods --all-namespaces -o jsonpath='{range .items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -f3

# 列出事件(Event),按時間戳排序
kubectl get events --sort-by=.metadata.creationTimestamp

# 列出所有警告事件
kubectl events --types=Warning

# 比較當前的叢集狀態和假定某清單被應用之後的叢集狀態
kubectl diff -f ./my-manifest.yaml

# 生成一個句點分隔的樹,其中包含為節點返回的所有鍵
# 在複雜的巢狀JSON結構中定位鍵時非常有用
kubectl get nodes -o json | jq -c 'paths|join(".")'

# 生成一個句點分隔的樹,其中包含為 Pod 等返回的所有鍵
kubectl get pods -o json | jq -c 'paths|join(".")'

# 假設你的 Pod 有默認的容器和默認的名字空間,並且支援 'env' 命令,可以使用以下指令碼為所有 Pod 生成 ENV 變數。
# 該指令碼也可用於在所有的 Pod 裡運行任何受支援的命令,而不僅僅是 'env'。
for pod in $(kubectl get po --output=jsonpath={.items..metadata.name}); do echo $pod && kubectl exec -it $pod -- env; done

# 獲取一個 Deployment 的 status 子資源
kubectl get deployment nginx-deployment --subresource=status

更新資源

kubectl set image deployment/frontend www=image:v2               # 滾動更新 "frontend" Deployment 的 "www" 容器鏡像
kubectl rollout history deployment/frontend                      # 檢查 Deployment 的歷史記錄,包括版本
kubectl rollout undo deployment/frontend                         # 回滾到上次部署版本
kubectl rollout undo deployment/frontend --to-revision=2         # 回滾到特定部署版本
kubectl rollout status -w deployment/frontend                    # 監視 "frontend" Deployment 的滾動升級狀態直到完成
kubectl rollout restart deployment/frontend                      # 輪替重啟 "frontend" Deployment

cat pod.json | kubectl replace -f -                              # 通過傳入到標準輸入的 JSON 來替換 Pod

# 強制替換,刪除後重建資源。會導致服務不可用。
kubectl replace --force -f ./pod.json

# 為多副本的 nginx 建立服務,使用 80 連接埠提供服務,連接到容器的 8000 連接埠
kubectl expose rc nginx --port=80 --target-port=8000

# 將某單容器 Pod 的鏡像版本(標籤)更新到 v4
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -

kubectl label pods my-pod new-label=awesome                      # 新增標籤
kubectl label pods my-pod new-label-                             # 移除標籤
kubectl label pods my-pod new-label=new-value --overwrite        # 覆蓋現有的值
kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq       # 新增註解
kubectl annotate pods my-pod icon-url-                           # 移除註解
kubectl autoscale deployment foo --min=2 --max=10                # 對 "foo" Deployment 自動擴縮容

部分更新資源

# 部分更新某節點
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'

# 更新容器的鏡像;spec.containers[*].name 是必需的。因為它是一個合併性質的主鍵。
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'

# 使用帶位置陣列的 JSON patch 更新容器的鏡像
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'

# 使用帶位置陣列的 JSON patch 停用某 Deployment 的 livenessProbe
kubectl patch deployment valid-deployment  --type json   -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'

# 在帶位置陣列中新增元素
kubectl patch sa default --type='json' -p='[{"op": "add", "path": "/secrets/1", "value": {"name": "whatever" } }]'

# 通過修正 scale 子資源來更新 Deployment 的副本數
kubectl patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{"spec":{"replicas":2}}'

編輯資源

kubectl edit svc/docker-registry                      # 編輯名為 docker-registry 的服務
KUBE_EDITOR="nano" kubectl edit svc/docker-registry   # 使用其他編輯器 (預設使用 vi)

對資源進行擴縮 (scale)

kubectl scale --replicas=3 rs/foo                                 # 將名為 'foo' 的副本集擴縮到 3 副本
kubectl scale --replicas=3 -f foo.yaml                            # 將在 "foo.yaml" 中的特定資源擴縮到 3 個副本
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql  # 如果名為 mysql 的 Deployment 的副本當前是 2,那麼將它擴縮到 3
kubectl scale --replicas=5 rc/foo rc/bar rc/baz                   # 擴縮多個副本控製器

刪除資源

kubectl delete -f ./pod.json                                              # 刪除在 pod.json 中指定的類型和名稱的 Pod
kubectl delete pod unwanted --now                                         # 刪除 Pod 且無寬限期限(無優雅時段)
kubectl delete pod,service baz foo                                        # 刪除名稱為 "baz" 和 "foo" 的 Pod 和服務
kubectl delete pods,services -l name=myLabel                              # 刪除包含 name=myLabel 標籤的 Pod 和服務
kubectl -n my-ns delete pod,svc --all                                     # 刪除在 my-ns 名字空間中全部的 Pod 和服務
# 刪除所有與 pattern1 或 pattern2 awk 模式匹配的 Pod
kubectl get pods  -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs  kubectl delete -n mynamespace pod
# 立刻強制刪除 Pod
kubectl delete pod my-pod --grace-period=0 --force

與運行中的 Pod 進行互動

kubectl logs my-pod                                 # 獲取 Pod 日誌(標準輸出)
kubectl logs -l name=myLabel                        # 獲取含 name=myLabel 標籤的 Pod 的日誌(標準輸出)
kubectl logs my-pod --previous                      # 獲取上個容器實例的 Pod 日誌(標準輸出)
kubectl logs my-pod -c my-container                 # 獲取 Pod 容器的日誌(標準輸出, 多容器場景)
kubectl logs -l name=myLabel -c my-container        # 獲取含 name=myLabel 標籤的 Pod 容器日誌(標準輸出, 多容器場景)
kubectl logs my-pod -c my-container --previous      # 獲取 Pod 中某容器的上個實例的日誌(標準輸出, 多容器場景)
kubectl logs -f my-pod                              # 流式輸出 Pod 的日誌(標準輸出)
kubectl logs -f my-pod -c my-container              # 流式輸出 Pod 容器的日誌(標準輸出, 多容器場景)
kubectl logs -f -l name=myLabel --all-containers    # 流式輸出含 name=myLabel 標籤的 Pod 的所有日誌(標準輸出)
kubectl run -i --tty busybox --image=busybox:1.28 -- sh  # 以互動式 Shell 運行 Pod
kubectl run nginx --image=nginx -n mynamespace      # 在 “mynamespace” 命名空間中運行單個 nginx Pod
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml
                                                    # 為運行 nginx Pod 生成規約並將其寫入到名為 pod.yaml 的檔案

kubectl attach my-pod -i                            # 掛接到一個運行的容器中
kubectl port-forward my-pod 5000:6000               # 在本地電腦上偵聽連接埠 5000 並轉發到 my-pod 上的連接埠 6000
kubectl exec my-pod -- ls /                         # 在已有的 Pod 中運行命令(單容器場景)
kubectl exec --stdin --tty my-pod -- /bin/sh        # 使用互動 shell 訪問正在運行的 Pod (一個容器場景)
kubectl exec my-pod -c my-container -- ls /         # 在已有的 Pod 中運行命令(多容器場景)
kubectl debug my-pod -it --image=busybox:1.28       # 在現有 Pod 中建立互動式偵錯會話並立即附加到此 Pod 上
kubectl debug node/my-node -it --image=busybox:1.28 # 在節點上建立互動式偵錯會話並立即附加到此節點上
kubectl top pod                                     # 顯示默認命名空間中所有 Pod 的度量值
kubectl top pod POD_NAME --containers               # 顯示給定 Pod 和其中容器的度量值
kubectl top pod POD_NAME --sort-by=cpu              # 顯示給定 Pod 的指標並且按照 'cpu' 或者 'memory' 排序

從容器中複製檔案和目錄

kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dir            # 將 /tmp/foo_dir 本地目錄複製到遠端當前命名空間中 Pod 中的 /tmp/bar_dir
kubectl cp /tmp/foo my-pod:/tmp/bar -c my-container    # 將 /tmp/foo 本地檔案複製到遠端 Pod 中特定容器的 /tmp/bar 下
kubectl cp /tmp/foo my-namespace/my-pod:/tmp/bar       # 將 /tmp/foo 本地檔案複製到遠端 “my-namespace” 命名空間內指定 Pod 中的 /tmp/bar
kubectl cp my-namespace/my-pod:/tmp/foo /tmp/bar       # 將 /tmp/foo 從遠端 Pod 複製到本地 /tmp/bar

說明:

kubectl cp 要求容器鏡像中存在 “tar” 二進制檔案。如果 “tar” 不存在,kubectl cp 將失敗。 對於進階用例,例如符號連結、萬用字元擴展或保留檔案權限,請考慮使用 kubectl exec

tar cf - /tmp/foo | kubectl exec -i -n my-namespace my-pod -- tar xf - -C /tmp/bar  # 將 /tmp/foo 本地檔案複製到遠端 “my-namespace” 命名空間中 Pod 中的 /tmp/bar
kubectl exec -n my-namespace my-pod -- tar cf - /tmp/foo | tar xf - -C /tmp/bar    # 將 /tmp/foo 從遠端 Pod 複製到本地 /tmp/bar

與 Deployments 和 Services 進行互動

kubectl logs deploy/my-deployment                         # 獲取一個 Deployment 的 Pod 的日誌(單容器例子)
kubectl logs deploy/my-deployment -c my-container         # 獲取一個 Deployment 的 Pod 的日誌(多容器例子)

kubectl port-forward svc/my-service 5000                  # 偵聽本機連接埠 5000 並轉發到 Service 後端連接埠 5000
kubectl port-forward svc/my-service 5000:my-service-port  # 偵聽本機連接埠 5000 並轉發到名字為 <my-service-port> 的 Service 目標連接埠

kubectl port-forward deploy/my-deployment 5000:6000       # 偵聽本機連接埠 5000 並轉發到 <my-deployment> 建立的 Pod 裡的連接埠 6000
kubectl exec deploy/my-deployment -- ls                   # 在 Deployment 裡的第一個 Pod 的第一個容器裡運行命令(單容器和多容器例子)

與節點和叢集進行互動

kubectl cordon my-node                                                # 標記 my-node 節點為不可調度
kubectl drain my-node                                                 # 對 my-node 節點進行清空操作,為節點維護做準備
kubectl uncordon my-node                                              # 標記 my-node 節點為可以調度
kubectl top node                                                      # 顯示所有節點的度量值
kubectl top node my-node                                              # 顯示給定節點的度量值
kubectl cluster-info                                                  # 顯示主控節點和服務的地址
kubectl cluster-info dump                                             # 將當前叢集狀態轉儲到標準輸出
kubectl cluster-info dump --output-directory=/path/to/cluster-state   # 將當前叢集狀態輸出到 /path/to/cluster-state

# 查看當前節點上存在的現有污點
kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect'

# 如果已存在具有指定鍵和效果的污點,則替換其值為指定值
kubectl taint nodes foo dedicated=special-user:NoSchedule

資源類型

列出所支援的全部資源類型和它們的簡稱、 API 組、 是否是名字空間範疇和 Kind

kubectl api-resources

用於探索 API 資源的其他操作:

kubectl api-resources --namespaced=true      # 所有命名空間範疇的資源
kubectl api-resources --namespaced=false     # 所有非命名空間範疇的資源
kubectl api-resources -o name                # 用簡單格式列舉所有資源(僅顯示資源名稱)
kubectl api-resources -o wide                # 用擴展格式列舉所有資源(又稱 "wide" 格式)
kubectl api-resources --verbs=list,get       # 支援 "list" 和 "get" 請求動詞的所有資源
kubectl api-resources --api-group=extensions # "extensions" API 組中的所有資源

格式化輸出

要以特定格式將詳細資訊輸出到終端窗口,將 -o(或者 --output)參數新增到支援的 kubectl 命令中。

輸出格式 描述
-o=custom-columns=<spec> 使用逗號分隔的自訂列來列印表格
-o=custom-columns-file=<filename> 使用 <filename> 檔案中的自訂列範本列印表格
-o=go-template=<template> 列印在 golang 範本中定義的欄位
-o=go-template-file=<filename> 列印在 <filename> 檔案中由 golang 範本定義的欄位
-o=json 輸出 JSON 格式的 API 對象
-o=jsonpath=<template> 列印 jsonpath 表示式中定義的欄位
-o=jsonpath-file=<filename> 列印在 <filename> 檔案中定義的 jsonpath 表示式所指定的欄位
-o=name 僅列印資源名稱而不列印其他內容
-o=wide 以純文字格式輸出額外資訊,對於 Pod 來說,輸出中包含了節點名稱
-o=yaml 輸出 YAML 格式的 API 對象

使用 -o=custom-columns 的示例:

# 叢集中運行著的所有鏡像
kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'

# 列舉 default 名字空間中運行的所有鏡像,按 Pod 分組
kubectl get pods --namespace default --output=custom-columns="NAME:.metadata.name,IMAGE:.spec.containers[*].image"

# 除 "registry.k8s.io/coredns:1.6.2" 之外的所有鏡像
kubectl get pods -A -o=custom-columns='DATA:spec.containers[?(@.image!="registry.k8s.io/coredns:1.6.2")].image'

# 輸出 metadata 下面的所有欄位,無論 Pod 名字為何
kubectl get pods -A -o=custom-columns='DATA:metadata.*'

取得幫助

kubectl 的指令數不勝數,無法把全部的用法都展示出來,若在使用上遇到困難,只需要在指令後面加上 -h 就可以取得說明和範例

kubectl get pods -h

結果如下

Display one or many resources.

 Prints a table of the most important information about the specified resources. You can filter the
list using a label selector and the --selector flag. If the desired resource type is namespaced you
will only see results in your current namespace unless you pass --all-namespaces.

 By specifying the output as 'template' and providing a Go template as the value of the --template
flag, you can filter the attributes of the fetched resources.

Use "kubectl api-resources" for a complete list of supported resources.

Examples:
  # List all pods in ps output format
  kubectl get pods

  # List all pods in ps output format with more information (such as node name)
  kubectl get pods -o wide

  # List a single replication controller with specified NAME in ps output format
  kubectl get replicationcontroller web

  # List deployments in JSON output format, in the "v1" version of the "apps" API group
  kubectl get deployments.v1.apps -o json

  # List a single pod in JSON output format
  kubectl get -o json pod web-pod-13je7

  # List a pod identified by type and name specified in "pod.yaml" in JSON output format
  kubectl get -f pod.yaml -o json

  # List resources from a directory with kustomization.yaml - e.g. dir/kustomization.yaml
  kubectl get -k dir/

  # Return only the phase value of the specified pod
  kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}

  # List resource information in custom columns
  kubectl get pod test-pod -o
custom-columns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image

  # List all replication controllers and services together in ps output format
  kubectl get rc,services

  # List one or more resources by their type and names
  kubectl get rc/web service/frontend pods/web-pod-13je7

  # List the 'status' subresource for a single pod
  kubectl get pod web-pod-13je7 --subresource status

Options:
    -A, --all-namespaces=false:
        If present, list the requested object(s) across all namespaces. Namespace in current
        context is ignored even if specified with --namespace.

    --allow-missing-template-keys=true:
        If true, ignore any errors in templates when a field or map key is missing in the
        template. Only applies to golang and jsonpath output formats.

    --chunk-size=500:
        Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta
        and may change in the future.

    --field-selector='':
        Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector
        key1=value1,key2=value2). The server only supports a limited number of field queries per
        type.

    -f, --filename=[]:
        Filename, directory, or URL to files identifying the resource to get from a server.

    --ignore-not-found=false:
        If the requested object does not exist the command will return exit code 0.

    -k, --kustomize='':
        Process the kustomization directory. This flag can't be used together with -f or -R.

    -L, --label-columns=[]:
        Accepts a comma separated list of labels that are going to be presented as columns. Names
        are case-sensitive. You can also use multiple flag options like -L label1 -L label2...

    --no-headers=false:
        When using the default or custom-column output format, don't print headers (default print
        headers).

    -o, --output='':
        Output format. One of: (json, yaml, name, go-template, go-template-file, template,
        templatefile, jsonpath, jsonpath-as-json, jsonpath-file, custom-columns,
        custom-columns-file, wide). See custom columns
        [https://kubernetes.io/docs/reference/kubectl/#custom-columns], golang template
        [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template
        [https://kubernetes.io/docs/reference/kubectl/jsonpath/].

    --output-watch-events=false:
        Output watch event objects when --watch or --watch-only is used. Existing objects are
        output as initial ADDED events.

    --raw='':
        Raw URI to request from the server.  Uses the transport specified by the kubeconfig file.

    -R, --recursive=false:
        Process the directory used in -f, --filename recursively. Useful when you want to manage
        related manifests organized within the same directory.

    -l, --selector='':
        Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l
        key1=value1,key2=value2). Matching objects must satisfy all of the specified label
        constraints.

    --server-print=true:
        If true, have the server return the appropriate table output. Supports extension APIs and
        CRDs.

    --show-kind=false:
        If present, list the resource type for the requested object(s).

    --show-labels=false:
        When printing, show all labels as the last column (default hide labels column)

    --show-managed-fields=false:
        If true, keep the managedFields when printing objects in JSON or YAML format.

    --sort-by='':
        If non-empty, sort list types using this field specification.  The field specification is
        expressed as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API
        resource specified by this JSONPath expression must be an integer or a string.

    --subresource='':
        If specified, gets the subresource of the requested object. Must be one of [status scale].
        This flag is beta and may change in the future.

    --template='':
        Template string or path to template file to use when -o=go-template, -o=go-template-file.
        The template format is golang templates
        [http://golang.org/pkg/text/template/#pkg-overview].

    -w, --watch=false:
        After listing/getting the requested object, watch for changes.

    --watch-only=false:
        Watch for changes to the requested object(s), without listing/getting first.

Usage:
  kubectl get
[(-o|--output=)json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file|custom-columns|custom-columns-file|wide]
(TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags] [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

小結

在掌握了如何使用 kubectl 之後,我們就擁有了與 Kubernetes 叢集溝通的手段。現在,我們終於可以正式進入 K8s 的世界了。

參考


上一篇
學 Kubernetes 的第四天 - 建立 Kubernetes 叢集 - KinD
下一篇
學 Kubernetes 的第六天 - 部署你的第一個應用程式 (1) - Application & Image
系列文
都什麼年代了,還在學 Kubernetes13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言