1. 程式人生 > 實用技巧 >Kubernetes進階實戰讀書筆記:常用命令大全

Kubernetes進階實戰讀書筆記:常用命令大全

一、查詢相關

#檢視所有namespace的pods執行情況
kubectl get pods --all-namespaces
#檢視具體pods,記得後邊跟namespace名字哦
kubectl get pods kubernetes-dashboard-76479d66bb-nj8wr --namespace=kube-system
# 檢視pods具體資訊
kubectl get pods -o wide kubernetes-dashboard-76479d66bb-nj8wr --namespace=kube-system
# 檢視叢集健康狀態
kubectl get cs
# 獲取所有deployment
kubectl get deployment --all-namespaces
# 列出該 namespace 中的所有 pod 包括未初始化的
kubectl get pods --include-uninitialized
# 檢視deployment()
kubectl get deployment nginx-app
# 檢視rc和servers
kubectl get rc,services
# 檢視pods結構資訊(重點,通過這個看日誌分析錯誤)
# 對控制器和服務,node同樣有效
kubectl describe pods xxxxpodsname --namespace=xxxnamespace
# 其他控制器類似吧,就是kubectl get 控制器 控制器具體名稱
# 檢視pod日誌
kubectl logs $POD_NAME
# 檢視pod變數
kubectl exec my-nginx-5j8ok -- printenv | grep SERVICE

 k8s所有物件簡寫

[root@master ~]# kubectl api-resources 
NAME                              SHORTNAMES   APIGROUP                       NAMESPACED   KIND
bindings                                                                      true         Binding
componentstatuses                 cs                                          false        ComponentStatus
configmaps                        cm                                          true         ConfigMap
endpoints                         ep                                          true         Endpoints
events                            ev                                          true         Event
limitranges                       limits                                      true         LimitRange
namespaces                        ns                                          false        Namespace
nodes                             no                                          false        Node
persistentvolumeclaims            pvc                                         true         PersistentVolumeClaim
persistentvolumes                 pv                                          false        PersistentVolume
pods                              po                                          true         Pod
podtemplates                                                                  true         PodTemplate
replicationcontrollers            rc                                          true         ReplicationController
resourcequotas                    quota                                       true         ResourceQuota
secrets                                                                       true         Secret
serviceaccounts                   sa                                          true         ServiceAccount
services                          svc                                         true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io   false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io   false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io           false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io         false        APIService
controllerrevisions                            apps                           true         ControllerRevision
daemonsets                        ds           apps                           true         DaemonSet
deployments                       deploy       apps                           true         Deployment
replicasets                       rs           apps                           true         ReplicaSet
statefulsets                      sts          apps                           true         StatefulSet
tokenreviews                                   authentication.k8s.io          false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io           true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io           false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io           false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io           false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling                    true         HorizontalPodAutoscaler
cronjobs                          cj           batch                          true         CronJob
jobs                                           batch                          true         Job
certificatesigningrequests        csr          certificates.k8s.io            false        CertificateSigningRequest
leases                                         coordination.k8s.io            true         Lease
endpointslices                                 discovery.k8s.io               true         EndpointSlice
events                            ev           events.k8s.io                  true         Event
ingresses                         ing          extensions                     true         Ingress
nodes                                          metrics.k8s.io                 false        NodeMetrics
pods                                           metrics.k8s.io                 true         PodMetrics
ingressclasses                                 networking.k8s.io              false        IngressClass
ingresses                         ing          networking.k8s.io              true         Ingress
networkpolicies                   netpol       networking.k8s.io              true         NetworkPolicy
runtimeclasses                                 node.k8s.io                    false        RuntimeClass
poddisruptionbudgets              pdb          policy                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io      false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io      false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io      true         RoleBinding
roles                                          rbac.authorization.k8s.io      true         Role
priorityclasses                   pc           scheduling.k8s.io              false        PriorityClass
csidrivers                                     storage.k8s.io                 false        CSIDriver
csinodes                                       storage.k8s.io                 false        CSINode
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment

二、叢集資訊查詢

kubectl get cs # 叢集健康情況
kubectl cluster-info # 叢集核心元件執行情況
kubectl get namespaces # 表空間名
kubectl version # 版本
kubectl api-versions # API
kubectl get events # 檢視事件
kubectl get nodes //獲取全部節點
kubectl delete node k8s2 //刪除節點
kubectl rollout status deploy nginx-test

三、 建立

kubectl create -f ./nginx.yaml # 建立資源
kubectl create -f . # 建立當前目錄下的所有yaml資源
kubectl create -f ./nginx1.yaml -f ./mysql2.yaml # 使用多個檔案建立資源
kubectl create -f ./dir # 使用目錄下的所有清單檔案來建立資源
kubectl create -f https://git.io/vPieo # 使用 url 來建立資源
kubectl run -i --tty busybox --image=busybox ----建立帶有終端的pod
kubectl run nginx --image=nginx # 啟動一個 nginx 例項
kubectl run mybusybox --image=busybox --replicas=5 ----啟動多個pod
kubectl explain pods,svc # 獲取 pod 和 svc 的文件

四、更新

1、滾動更新

kubectl rolling-update python-v1 -f python-v2.json # 滾動更新 pod frontend-v1
kubectl rolling-update python-v1 python-v2 --image=image:v2 # 更新資源名稱並更新映象
kubectl rolling-update python --image=image:v2 # 更新 frontend pod 中的映象
kubectl rolling-update python-v1 python-v2 --rollback # 退出已存在的進行中的滾動更新

2、強制替換

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

3、更新單容器 pod 的映象版本(tag)到 v4

kubectl get pod nginx-pod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
kubectl label pods nginx-pod new-label=awesome # 新增標籤
kubectl annotate pods nginx-pod icon-url=http://goo.gl/XXBTWq # 添加註解
kubectl autoscale deployment foo --min=2 --max=10 # 自動擴充套件 deployment “foo”

4、編輯資源

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

5、動態伸縮pod

kubectl scale --replicas=3 rs/foo # 將foo副本集變成3個
kubectl scale --replicas=3 -f foo.yaml # 縮放“foo”中指定的資源。
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql # 將deployment/mysql從2個變成3個
kubectl scale --replicas=5 rc/foo rc/bar rc/baz # 變更多個控制器的數量
kubectl rollout status deploy deployment/mysql # 檢視變更進度

五、刪除

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,包括尚未初始化的
kubectl delete pods prometheus-7fcfcb9f89-qkkf7 --grace-period=0 --force 強制刪除

六、互動

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

七、 排程配置

$ kubectl cordon k8s-node # 標記 my-node 不可排程
$ kubectl drain k8s-node # 清空 my-node 以待維護
$ kubectl uncordon k8s-node # 標記 my-node 可排程
$ kubectl top node k8s-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