1.kubectl 命令補全
yum install -y bash-completion
source <(kubectl completion bash) #在bash中設置自動補全
echo "source <(kubectl completion bash)" >> ~/.bashrc
# source <(kubectl completion zsh) #在zsh中設置自動補全
2.kubectl上下文和配置
kubectl config view # 顯示合並后的kubeconfig配置
# 同時使用多個 kubeconfig 文件並查看合並后的配置
KUBECONFIG=~/.kube/config:~/.kube/config-2 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
3.創建對象
Kubernetes 的清單文件可以使用 json 或 yaml 格式定義。可以以 .yaml、.yml、或者 .json 為擴展名。
kubectl create -f ./app.yaml # 單個文件
kubectl create -f ./app.yaml ./app02.yaml #多個文件
kubectl create -f ./dir #目錄
kubectl create -f https://git.io/vPieo # 使用 url 來創建資源
kubectl run nginx --image=nginx #啟動一個nginx實例
kubectl explain pods #獲取pod的文檔
kubectl explain svc #獲取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 "s33msi4" | base64)
username: $(echo "jane" | base64)
EOF
4.顯示和查找資源
kubectl get services
kubectl get pods --all-namespaces
kuebctl get pods -o wide
kubectl get deployment my-dep
# 輸出描述信息
kubectl describe nodes my-node
kubectl describe pods my-pod
# 按服務名稱進行排序
kubectl get services --sort-by=.metadata.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}'
# 查看哪些節點已經就緒
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
5.更新資源
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 # 強制替換,刪除后重新創建資源。會導致服務中斷。
kubectl expose rc nginx --port=80 --target-port=8000 # 為nginx RC 創建服務,啟動本地80端口連接到容器上的8000端口
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f - # 更新單容器pod的鏡像版本(tag)到v4
kubectl label pods my-pod new-label=awesome #添加標簽
kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq #添加注解
kubectl autoscale deployment goo --min=2 --max=10 #自動擴展deployment “foo”
6.修補資源
$ 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"}]'
7.編輯資源
kubectl edit svc/docker-registry
KUBE_EDITOR="vim" kubectl edit svc/docker-registry # 使用其它編輯器
8.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
9.刪除資源
kubectl delete -f ./pod.json
kubectl delete -f ./pod.yaml
kubectl delete pods,service baz foo # 刪除pod baz 和svc foo
kubectl delete pods,services -l name=myLabel # 刪除具有name=myLabel標簽的pod和services
kubectl -n my-ns delete po,svc -all #刪除my-ns名稱空間下的所有pod和svc
10.與運行中的pod交互
kubectl logs mypod
kubectl logs mypod -c my-container #輸出pod中容器名稱為my-container的日志
kubectl logs -f mypod # 查詢pod的日志
kubectl logs -f --tail 500 mypod # 查詢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 mypod -- ls / #在容器中執行命令
kubectl exec my-pod -c my-container -- ls / # 在已存在的容器中執行命令(pod中有多個容器的情況下)
kubectl top pod pod-name --containers # 顯示指定pod和容器的指標度量
11.與節點和集群交互
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
kubectl taint nodes foo dedicated=special-user:NoSchedule ##如果該鍵和影響的污點(taint)已存在,則使用指定的值替換
12.資源類型
下表列出的是 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
13.格式化輸出
要以特定的格式向終端窗口輸出詳細信息,可以在 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 對象
14.Kubectl 詳細輸出和調試
使用 -v 或 --v 標志跟着一個整數來指定日志級別。
詳細等級 描述
--v=0 總是對操作人員可見。
--v=1 合理的默認日志級別,如果您不需要詳細輸出。
--v=2 可能與系統的重大變化相關的,有關穩定狀態的信息和重要的日志信息。這是對大多數系統推薦的日志級別。
--v=3 有關更改的擴展信息。
--v=4 調試級別詳細輸出。
--v=6 顯示請求的資源。
--v=7 顯示HTTP請求的header。
--v=8 顯示HTTP請求的內容。