kubectl 命令集合

轉(zhuǎn): https://www.cnblogs.com/hongdada/p/11327979.html

https://www.cnblogs.com/51wansheng/p/10249182.html

Kubectl 自動(dòng)補(bǔ)全#

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 上下文和配置#

設(shè)置 kubectl 命令交互的 kubernetes 集群并修改配置信息。參閱 使用 kubeconfig 文件進(jìn)行跨集群驗(yàn)證獲取關(guān)于配置文件的詳細(xì)信息。

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

同時(shí)使用多個(gè) kubeconfig 文件并查看合并后的配置

$ KUBECONFIG=/.kube/config:/.kube/kubconfig2 kubectl config view

獲取 e2e 用戶的密碼

$ kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'

kubectl config current-context # 顯示當(dāng)前的上下文 kubectl config use-context my-cluster-name # 設(shè)置默認(rèn)上下文為 my-cluster-name

向 kubeconf 中增加支持基本認(rèn)證的新集群

$ kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword

使用指定的用戶名和 namespace 設(shè)置上下文

$ kubectl config set-context gce --user=cluster-admin --namespace=foo && kubectl config use-context gce`</pre>

創(chuàng)建對(duì)象#

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

`kubectl create -f ./my-manifest.yaml # 創(chuàng)建資源 kubectl create -f ./my1.yaml -f ./my2.yaml # 使用多個(gè)文件創(chuàng)建資源
kubectl create -f ./dir # 使用目錄下的所有清單文件來(lái)創(chuàng)建資源 kubectl create -f https://git.io/vPieo # 使用 url 來(lái)創(chuàng)建資源
kubectl run nginx --image=nginx # 啟動(dòng)一個(gè) nginx 實(shí)例 kubectl explain pods,svc # 獲取 pod 和 svc 的文檔

從 stdin 輸入中創(chuàng)建多個(gè) YAML 對(duì)象

$ 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

創(chuàng)建包含幾個(gè) 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`</pre>

顯示和查找資源#

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

使用詳細(xì)輸出來(lái)描述命令

kubectl describe nodes my-node kubectl describe pods my-pod

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

根據(jù)重啟次數(shù)排序列出 pod

$ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

獲取所有具有 app=cassandra 的 pod 中的 version 標(biāo)簽

$ kubectl get pods --selector=app=cassandra rc -o
jsonpath='{.items[*].metadata.labels.version}'

獲取所有節(jié)點(diǎn)的 ExternalIP

$ kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'

列出屬于某個(gè) PC 的 Pod 的名字

“jq”命令用于轉(zhuǎn)換復(fù)雜的 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})

查看哪些節(jié)點(diǎn)已就緒

JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \ && kubectl get nodes -o jsonpath="JSONPATH" | grep "Ready=True"

列出當(dāng)前 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 -f frontend-v2.json # 滾動(dòng)更新 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 # 退出已存在的進(jìn)行中的滾動(dòng)更新
$ cat pod.json | kubectl replace -f - # 基于 stdin 輸入的 JSON 替換 pod

強(qiáng)制替換,刪除后重新創(chuàng)建資源。會(huì)導(dǎo)致服務(wù)中斷。

$ kubectl replace --force -f ./pod.json

為 nginx RC 創(chuàng)建服務(wù),啟用本地 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 # 添加標(biāo)簽 kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq # 添加注解
$ kubectl autoscale deployment foo --min=2 --max=10 # 自動(dòng)擴(kuò)展 deployment “foo”`</pre>

修補(bǔ)資源#

使用策略合并補(bǔ)丁并修補(bǔ)資源。

<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}}' # 部分更新節(jié)點(diǎn)

更新容器鏡像; spec.containers[*].name 是必須的,因?yàn)檫@是合并的關(guān)鍵字

$ kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'

使用具有位置數(shù)組的 json 補(bǔ)丁更新容器鏡像

$ kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'

使用具有位置數(shù)組的 json 補(bǔ)丁禁用 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 標(biāo)簽的 pod 和 serivce $ kubectl delete pods,services -l name=myLabel --include-uninitialized # 刪除具有 name=myLabel 標(biāo)簽的 pod 和 service,包括尚未初始化的 $ kubectl -n my-ns delete po,svc --all # 刪除 my-ns namespace 下的所有 pod 和 serivce,包括尚未初始化的</pre>

與運(yùn)行中的 Pod 交互#

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

與節(jié)點(diǎn)和集群交互#

`kubectl cordon my-node # 標(biāo)記 my-node 不可調(diào)度 kubectl drain my-node # 清空 my-node 以待維護(hù)
kubectl uncordon my-node # 標(biāo)記 my-node 可調(diào)度 kubectl top node my-node # 顯示 my-node 的指標(biāo)度量
kubectl cluster-info # 顯示 master 和服務(wù)的地址 kubectl cluster-info dump # 將當(dāng)前集群狀態(tài)輸出到 stdout
$ kubectl cluster-info dump --output-directory=/path/to/cluster-state # 將當(dāng)前集群狀態(tài)輸出到 /path/to/cluster-state

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

$ kubectl taint nodes foo dedicated=special-user:NoSchedule`</pre>

Kubectl可操作的資源對(duì)象類型#

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

資源類型 縮寫(xiě)別名
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格式化輸出#

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

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

Kubectl 詳細(xì)輸出和調(diào)試#

使用 -v--v 標(biāo)志跟著一個(gè)整數(shù)來(lái)指定日志級(jí)別。

詳細(xì)等級(jí) 描述
--v=0 總是對(duì)操作人員可見(jiàn)。
--v=1 合理的默認(rèn)日志級(jí)別,如果您不需要詳細(xì)輸出。
--v=2 可能與系統(tǒng)的重大變化相關(guān)的,有關(guān)穩(wěn)定狀態(tài)的信息和重要的日志信息。這是對(duì)大多數(shù)系統(tǒng)推薦的日志級(jí)別。
--v=3 有關(guān)更改的擴(kuò)展信息。
--v=4 調(diào)試級(jí)別詳細(xì)輸出。
--v=6 顯示請(qǐng)求的資源。
--v=7 顯示HTTP請(qǐng)求的header。
--v=8 顯示HTTP請(qǐng)求的內(nèi)容。

基礎(chǔ)操作#

重啟pod#

(無(wú)法刪除對(duì)應(yīng)的應(yīng)用,因?yàn)榇嬖赿eployment/rc之類的副本控制器,刪除pod也會(huì)重新拉起來(lái))

kubectl get pod -n kube-system</pre>

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

kubectl logs xxx -n kube-system</pre>

擴(kuò)容#

kubectl scale deployment spark-worker-deployment --replicas=8</pre>

導(dǎo)出配置文件:#

導(dǎo)出proxy#

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

導(dǎo)出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>

導(dǎo)出所有 configmap#

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

查看各組件信息#

kubectl get componentstatuses</pre>

設(shè)為不可調(diào)度狀態(tài):#

kubectl cordon node1</pre>

將pod趕到其他節(jié)點(diǎn):#

kubectl drain node1</pre>

解除不可調(diào)度狀態(tài)#

kubectl uncordon node1</pre>

master運(yùn)行pod#

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

master不運(yùn)行pod#

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

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

$ kubectl taint nodes foo dedicated=special-user:NoSchedule</pre>

參考:#

Kubectl基本操作命令

kubectl 命令技巧大全

kubectl kubernetes cheatsheet

CHEATSHEET

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 排錯(cuò)指南 - Pod 本文檔介紹 Pod 的異常狀態(tài),可能原因和解決辦法。 排查 Pod 異常的常用命令如下: 查...
    小孩子的童話2014閱讀 7,030評(píng)論 0 2
  • python 常用運(yùn)算符 1-成員運(yùn)算符 in 、not in str = 'shxt' for i in str...
    源程序程序員閱讀 66評(píng)論 0 1
  • 前言: 在Android 和iOS 常用的App里面經(jīng)常獲取地址的地址選擇器 ,android和iO...
    xq9527閱讀 2,048評(píng)論 1 5
  • 1. 命名規(guī)范 1.1 概述 描述了了關(guān)于RPA開(kāi)發(fā)過(guò)程中的各種文件、參數(shù)的命名規(guī)范。 1.2 文件夾及文件 需要...
    年少有為吾詩(shī)悅閱讀 1,640評(píng)論 0 0
  • 《the psychology of selling》 Back Your Goal with Persisten...
    董文楠閱讀 156評(píng)論 0 0