轉: https://www.cnblogs.com/hongdada/p/11327979.html
https://www.cnblogs.com/51wansheng/p/10249182.html
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
</pre>
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 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`</pre>
創建對象#
Kubernetes 的清單文件可以使用 json 或 yaml 格式定義。可以以 .yaml
、.yml
、或者 .json
為擴展名。
` kubectl create -f ./my1.yaml -f ./my2.yaml # 使用多個文件創建資源
kubectl create -f https://git.io/vPieo # 使用 url 來創建資源
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
(echo "hongdadada" | base64)
username: $(echo "hongda" | base64)
EOF`</pre>
顯示和查找資源#
`# Get commands with basic output
kubectl get pods --all-namespaces # 列出所有 namespace 中的所有 pod
kubectl get deployment my-dep # 列出指定 deployment
$ kubectl get pods --include-uninitialized # 列出該 namespace 中的所有 pod 包括未初始化的
使用詳細輸出來描述命令
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/
{
echo
sel --output=jsonpath={.items..metadata.name})
查看哪些節點已就緒
JSONPATH" | grep "Ready=True"
列出當前 Pod 中使用的 Secret
$ kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq`</pre>
更新資源#
` kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2 # 更新資源名稱并更新鏡像
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
/\1:v4/' | kubectl replace -f -
kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq # 添加注解
$ kubectl autoscale deployment foo --min=2 --max=10 # 自動擴展 deployment “foo”`</pre>
修補資源#
使用策略合并補丁并修補資源。
<pre class="bash" style="margin: 10px 0px; padding: 0px; white-space: pre !important; overflow-wrap: break-word; position: relative !important; color: rgb(49, 70, 89); font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 300; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
Copy
`$ 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"}]'`</pre>
編輯資源#
在編輯器中編輯任何 API 資源。
<pre class="bash" style="margin: 10px 0px; padding: 0px; white-space: pre !important; overflow-wrap: break-word; position: relative !important; color: rgb(49, 70, 89); font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 300; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
Copy
$ kubectl edit svc/docker-registry # 編輯名為 docker-registry 的 service $ KUBE_EDITOR="nano" kubectl edit svc/docker-registry # 使用其它編輯器
</pre>
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
</pre>
刪除資源#
$ 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,包括尚未初始化的
</pre>
與運行中的 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 和容器的指標度量
</pre>
與節點和集群交互#
` kubectl drain my-node # 清空 my-node 以待維護
kubectl top node my-node # 顯示 my-node 的指標度量
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`</pre>
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
</pre>
查看pod 日志 (如果pod有多個容器需要加-c 容器名)#
kubectl logs xxx -n kube-system
</pre>
擴容#
kubectl scale deployment spark-worker-deployment --replicas=8
</pre>
導出配置文件:#
導出proxy#
kubectl get ds -n kube-system -l k8s-app=kube-proxy -o yaml>kube-proxy-ds.yaml
</pre>
導出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
</pre>
導出所有 configmap#
kubectl get configmap -n kube-system -o wide -o yaml > configmap.yaml
</pre>
查看各組件信息#
kubectl get componentstatuses
</pre>
設為不可調度狀態:#
kubectl cordon node1
</pre>
將pod趕到其他節點:#
kubectl drain node1
</pre>
解除不可調度狀態#
kubectl uncordon node1
</pre>
master運行pod#
kubectl taint nodes master.k8s node-role.kubernetes.io/master-
</pre>
master不運行pod#
kubectl taint nodes master.k8s node-role.kubernetes.io/master=:NoSchedule
</pre>
如果該鍵和影響的污點(taint)已存在,則使用指定的值替換#
$ kubectl taint nodes foo dedicated=special-user:NoSchedule
</pre>