Kubectl操作命令


Kubectl 自動補全

yum install -y bash-completion
source /usr/share/bash-completion/bash_completion


$ source <(kubectl completion bash) # setup autocomplete in bash, bash-completion package should be installed first.
$ source <(kubectl completion zsh)  # setup autocomplete in zsh

Kubectl 上下文和配置

設置 kubectl 命令交互的 kubernetes 集群並修改配置信息。參閱 使用 kubeconfig 文件進行跨集群驗證獲取關於配置文件的詳細信息。

$ kubectl config view # 顯示合並后的 kubeconfig 配置

# 同時使用多個 kubeconfig 文件並查看合並后的配置
$ KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config view

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

$ kubectl config current-context              # 顯示當前的上下文
$ kubectl config use-context my-cluster-name  # 設置默認上下文為 my-cluster-name

# 向 kubeconf 中增加支持基本認證的新集群
$ kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword

# 使用指定的用戶名和 namespace 設置上下文
$ kubectl config set-context gce --user=cluster-admin --namespace=foo && kubectl config use-context gce

創建對象

Kubernetes 的清單文件可以使用 json 或 yaml 格式定義。可以以 .yaml.yml、或者 .json 為擴展名。

$ kubectl create -f ./my-manifest.yaml           # 創建資源
$ kubectl create -f ./my1.yaml -f ./my2.yaml     # 使用多個文件創建資源
$ kubectl create -f ./dir                        # 使用目錄下的所有清單文件來創建資源
$ kubectl create -f https://git.io/vPieo         # 使用 url 來創建資源
$ kubectl run nginx --image=nginx                # 啟動一個 nginx 實例
$ kubectl explain pods,svc                       # 獲取 pod 和 svc 的文檔

# 從 stdin 輸入中創建多個 YAML 對象
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
  name: busybox-sleep
spec:
  containers:
  - name: busybox
    image: busybox
    args:
    - sleep
    - "1000000"
---
apiVersion: v1
kind: Pod
metadata:
  name: busybox-sleep-less
spec:
  containers:
  - name: busybox
    image: busybox
    args:
    - sleep
    - "1000"
EOF

# 創建包含幾個 key 的 Secret
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  password: $(echo "hongdadada" | base64)
  username: $(echo "hongda" | base64)
EOF

顯示和查找資源

# Get commands with basic output
$ kubectl get services                          # 列出所有 namespace 中的所有 service
$ kubectl get pods --all-namespaces             # 列出所有 namespace 中的所有 pod
$ kubectl get pods -o wide                      # 列出所有 pod 並顯示詳細信息
$ kubectl get deployment my-dep                 # 列出指定 deployment
$ kubectl get pods --include-uninitialized      # 列出該 namespace 中的所有 pod 包括未初始化的

# 使用詳細輸出來描述命令
$ kubectl describe nodes my-node
$ kubectl describe pods my-pod

$ kubectl get services --sort-by=.metadata.name # List Services Sorted by Name

# 根據重啟次數排序列出 pod
$ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

# 獲取所有具有 app=cassandra 的 pod 中的 version 標簽
$ kubectl get pods --selector=app=cassandra rc -o \
  jsonpath='{.items[*].metadata.labels.version}'

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

# 列出屬於某個 PC 的 Pod 的名字
# “jq”命令用於轉換復雜的 jsonpath,參考 https://stedolan.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})

# 查看哪些節點已就緒
$ JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
 && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"

# 列出當前 Pod 中使用的 Secret
$ kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq

更新資源

$ kubectl rolling-update frontend-v1 -f frontend-v2.json           # 滾動更新 pod frontend-v1
$ kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2  # 更新資源名稱並更新鏡像
$ kubectl rolling-update frontend --image=image:v2                 # 更新 frontend pod 中的鏡像
$ kubectl rolling-update frontend-v1 frontend-v2 --rollback        # 退出已存在的進行中的滾動更新
$ cat pod.json | kubectl replace -f -                              # 基於 stdin 輸入的 JSON 替換 pod

# 強制替換,刪除后重新創建資源。會導致服務中斷。
$ kubectl replace --force -f ./pod.json

# 為 nginx RC 創建服務,啟用本地 80 端口連接到容器上的 8000 端口
$ kubectl expose rc nginx --port=80 --target-port=8000

# 更新單容器 pod 的鏡像版本(tag)到 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 annotate pods my-pod icon-url=http://goo.gl/XXBTWq       # 添加注解
$ kubectl autoscale deployment foo --min=2 --max=10                # 自動擴展 deployment “foo”

修補資源

使用策略合並補丁並修補資源。

$ 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 補丁更新容器鏡像
$ kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'

# 使用具有位置數組的 json 補丁禁用 deployment 的 livenessProbe
$ kubectl patch deployment valid-deployment  --type json   -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'

編輯資源

在編輯器中編輯任何 API 資源。

$ kubectl edit svc/docker-registry                      # 編輯名為 docker-registry 的 service
$ KUBE_EDITOR="nano" kubectl edit svc/docker-registry   # 使用其它編輯器

Scale 資源

$ kubectl scale --replicas=3 rs/foo                                 # Scale a replicaset named 'foo' to 3
$ kubectl scale --replicas=3 -f foo.yaml                            # Scale a resource specified in "foo.yaml" to 3
$ kubectl scale --current-replicas=2 --replicas=3 deployment/mysql  # If the deployment named mysql's current size is 2, scale mysql to 3
$ kubectl scale --replicas=5 rc/foo rc/bar rc/baz                   # Scale multiple replication controllers

刪除資源

$ kubectl delete -f ./pod.json                                              # 刪除 pod.json 文件中定義的類型和名稱的 pod
$ kubectl delete pod,service baz foo                                        # 刪除名為“baz”的 pod 和名為“foo”的 service
$ kubectl delete pods,services -l name=myLabel                              # 刪除具有 name=myLabel 標簽的 pod 和 serivce
$ kubectl delete pods,services -l name=myLabel --include-uninitialized      # 刪除具有 name=myLabel 標簽的 pod 和 service,包括尚未初始化的
$ kubectl -n my-ns delete po,svc --all                                      # 刪除 my-ns namespace 下的所有 pod 和 serivce,包括尚未初始化的

與運行中的 Pod 交互

$ kubectl logs my-pod                                 # dump 輸出 pod 的日志(stdout)
$ kubectl logs my-pod -c my-container                 # dump 輸出 pod 中容器的日志(stdout,pod 中有多個容器的情況下使用)
$ kubectl logs -f my-pod                              # 流式輸出 pod 的日志(stdout)
$ kubectl logs -f my-pod -c my-container              # 流式輸出 pod 中容器的日志(stdout,pod 中有多個容器的情況下使用)
$ kubectl run -i --tty busybox --image=busybox -- sh  # 交互式 shell 的方式運行 pod
$ kubectl attach my-pod -i                            # 連接到運行中的容器
$ kubectl port-forward my-pod 5000:6000               # 轉發 pod 中的 6000 端口到本地的 5000 端口
$ kubectl exec my-pod -- ls /                         # 在已存在的容器中執行命令(只有一個容器的情況下)
$ kubectl exec my-pod -c my-container -- ls /         # 在已存在的容器中執行命令(pod 中有多個容器的情況下)
$ kubectl top pod POD_NAME --containers               # 顯示指定 pod 和容器的指標度量

與節點和集群交互

$ kubectl cordon my-node                                                # 標記 my-node 不可調度
$ kubectl drain my-node                                                 # 清空 my-node 以待維護
$ kubectl uncordon my-node                                              # 標記 my-node 可調度
$ kubectl top node my-node                                              # 顯示 my-node 的指標度量
$ kubectl cluster-info                                                  # 顯示 master 和服務的地址
$ kubectl cluster-info dump                                             # 將當前集群狀態輸出到 stdout                                    
$ kubectl cluster-info dump --output-directory=/path/to/cluster-state   # 將當前集群狀態輸出到 /path/to/cluster-state

# 如果該鍵和影響的污點(taint)已存在,則使用指定的值替換
$ kubectl taint nodes foo dedicated=special-user:NoSchedule

Kubectl可操作的資源對象類型

下表列出的是 kubernetes 中所有支持的類型和縮寫的別名。

資源類型 縮寫別名
clusters
componentstatuses cs
configmaps cm
daemonsets ds
deployments deploy
endpoints ep
event ev
horizontalpodautoscalers hpa
ingresses ing
jobs
limitranges limits
namespaces ns
networkpolicies
nodes no
statefulsets
persistentvolumeclaims pvc
persistentvolumes pv
pods po
podsecuritypolicies psp
podtemplates
replicasets rs
replicationcontrollers rc
resourcequotas quota
cronjob
secrets
serviceaccount sa
services svc
storageclasses
thirdpartyresources

Kubectl格式化輸出

要以特定的格式向終端窗口輸出詳細信息,可以在 kubectl 命令中添加 -o 或者 -output 標志。

輸出格式 描述
-o=custom-columns=<spec> 使用逗號分隔的自定義列列表打印表格
-o=custom-columns-file=<filename> 使用 文件中的自定義列模板打印表格
-o=json 輸出 JSON 格式的 API 對象
-o=jsonpath=<template> 打印 jsonpath 表達式中定義的字段
-o=jsonpath-file=<filename> 打印由 文件中的 jsonpath 表達式定義的字段
-o=name 僅打印資源名稱
-o=wide 以純文本格式輸出任何附加信息,對於 Pod ,包含節點名稱
-o=yaml 輸出 YAML 格式的 API 對象

Kubectl 詳細輸出和調試

使用 -v--v 標志跟着一個整數來指定日志級別。

詳細等級 描述
--v=0 總是對操作人員可見。
--v=1 合理的默認日志級別,如果您不需要詳細輸出。
--v=2 可能與系統的重大變化相關的,有關穩定狀態的信息和重要的日志信息。這是對大多數系統推薦的日志級別。
--v=3 有關更改的擴展信息。
--v=4 調試級別詳細輸出。
--v=6 顯示請求的資源。
--v=7 顯示HTTP請求的header。
--v=8 顯示HTTP請求的內容。

基礎操作

重啟pod

(無法刪除對應的應用,因為存在deployment/rc之類的副本控制器,刪除pod也會重新拉起來)

kubectl get pod -n kube-system

查看pod 日志 (如果pod有多個容器需要加-c 容器名)

kubectl logs xxx -n kube-system

擴容

kubectl scale deployment spark-worker-deployment --replicas=8

導出配置文件:

導出proxy

 kubectl get ds -n kube-system -l k8s-app=kube-proxy -o yaml>kube-proxy-ds.yaml

導出kube-dns

kubectl get deployment -n kube-system -l k8s-app=kube-dns -o yaml >kube-dns-dp.yaml
kubectl get services -n kube-system -l k8s-app=kube-dns -o yaml >kube-dns-services.yaml

導出所有 configmap

kubectl get configmap -n kube-system -o wide -o yaml > configmap.yaml

查看各組件信息

kubectl get componentstatuses

設為不可調度狀態:

kubectl cordon node1

將pod趕到其他節點:

kubectl drain node1

解除不可調度狀態

kubectl uncordon node1

master運行pod

kubectl taint nodes master.k8s node-role.kubernetes.io/master-

master不運行pod

kubectl taint nodes master.k8s node-role.kubernetes.io/master=:NoSchedule

如果該鍵和影響的污點(taint)已存在,則使用指定的值替換

$ kubectl taint nodes foo dedicated=special-user:NoSchedule

參考:

Kubectl基本操作命令

kubectl 命令技巧大全

kubectl kubernetes cheatsheet

CHEATSHEET


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM