kubectl 詳細命令用法可以參考官網:
https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands
常用命令:
查看
- 只顯示默認命名空間的pods
kubectl get pods
- 顯示所有空間的pod
kubectl get pods --all-namespaces
- 顯示指定空間的pod
kubectl get pods -o wide --namespace apm
其中--namespace 與-n 作用等同,后面接命名空間參數 kubectl get deployment -n apm
kubectl get pods,svc,rc -n apm svc是services簡稱 這些命令都可以通過 kubectl get --help 來查看幫助
刪除
- 只能刪除默認命名空間的deployment
kubectl delete deployment nginx
- 刪除指定空間的deployment/其他資源等
kubectl delete TYPE RESOURCE -n NAMESPACE 具體如下: kubectl delete deployment shop-app -n test-shop kubectl delete TYPE --all -n NAMESPACE kubectl delete all -n NAMESPACE kubectl delete all --all
創建、修改、打標簽
- 使用yaml文件創建pod
kubectl apply -f apptrace-receiver-deployment.yaml
apply 和 create 命令都可以后跟yaml,創建所需資源,初次創建pod時可以互相替換使用;如果已有pod只是用於更新的話,又可以和replace相互替換使用;本着化繁就簡的原則,create和replace都使用apply; 而且apply屬於申明式語法,這個更加靈活,多次執行不會報錯,只會更新改變的部分;像Jenkinsfile也已經從腳本語法向申明式轉變。
- 使用kubectl命令把pod、卷、各種資源導出為yaml格式:
kubectl get pods podA -n NAMEAPSCE-A -o yaml --export> padA.yaml pod 可以換成其他申明式資源如卷、services等;如果不帶上參數--export 目前沒有發現有特別大的不同 kubectl get all -n ns -o yaml --export> padA.yaml #導出某個命令空間所有資源
現在很多產品如rancher openshift,等;UI界面 直接可視化操作導出各種資源,掌握命令很多時候,可以事半功倍。-o更詳細用法 下面有單獨說明。
- 查看命名空間apm的collector服務詳情
```kubectl describe service/apptrace-collector --namespace apm --namespace 和-n 作用相同
- 查看pod日志 ```kubectl logs podname --namespace apm (可以帶上 -f 參數)
- 為節點機apm-docker001打標簽 zookeeper-node=apm-docker001,查看標簽等;
為節點機打標簽和查看 kubectl label nodes apm-docker001 zookeeper-node=apm-docker001 kubectl get nodes --show-labels 為命名空間打標簽和查看 kubectl label namespace $your-namesapce istio-injection=enabled kubectl get namespaces --show-labels
- 給名為foo的Pod添加label unhealthy=true
kubectl label pods foo unhealthy=true
- 查看某種類型字段下有哪些參數;
kubectl explain pods kubectl explain Deployment kubectl explain Deployment.spec kubectl explain Deployment.spec.spec kubectl explain Deployment.spec.template kubectl explain Deployment.spec.template.spec
如查看Deployment.spec.template 可以有哪些參數 [root@k8s-master ~]# kubectl explain Deployment.spec.template KIND: Deployment VERSION: extensions/v1beta1 RESOURCE: template <Object> DESCRIPTION: Template describes the pods that will be created. PodTemplateSpec describes the data a pod should have when created from a template FIELDS: metadata <Object> Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata spec <Object> Specification of the desired behavior of the pod. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
- 在pod內部,執行shell命令
kubectl exec podname printenv | ps aux | cat、ls 某個文件(如果pod不在默認空間,用-n 指定相應空間) 如:kubectl exec app-demo-68b4bd9759-sfpcf -n test-shop printenv 或者在kubectl exec podname -- 再跟shell命令 如: kubectl exec -it spark-master-xksl -c spark-master -n spark -- mkdir -p /usr/local/spark shell命令前,要加-- 號,不然shell命令中的參數,不能識別 kubectl exec 后面只能是pod,目前還不支持deployment daemonnset等
特別說明
創建和修改相對復雜些,可以直接在rancherUI 進行部署或者修改,修改還可以通過:kubectl edit deploy/xxx -n namespace,也可以把資源導出為yaml后,修改完成后,再次kubectl apply 部署一遍完成修改的目的。本人推薦通過rancherUI來部署和修改,這里就不對創建和修改做詳細說明了;參考另一篇博客rancher 中快速部署應用
"-"在kubectl中 用法說明
“-”它作為標准輸入(池)非常靈活用法 ,和tar中用法非常類似
-
yaml
- apiVersion: v1 data: kubernetes.yml: |- - type: docker containers.ids: - "*" processors: - add_kubernetes_metadata: in_cluster: true kind: ConfigMap
- 命令
kubectl get po --all-namespaces --show-all --field-selector 'status.phase==Pending' -o json | kubectl delete -f -
curl --insecure -sfL https://your_domain/v3/import/f2gdpkvz42gqzm8vbrdpd99xgppjxgwct7wt86lzswwnf4p2d4vfd7.yaml | kubectl apply -f -
可以看出,“-”里面保存標准輸入的內容。
巧用kubectl 幫助文件
如你只記得部分命令 get ,可以用 kubectl get --help
同理 kubectl create rolebinding
不知道后面接什么 也可以--help一下,記得關鍵字越多 帶上后再使用help,如果只記得部分 就先help 如 kubectl create --help
這樣create 所有類型的應用怎么創建 都有了 同樣也可以直接 kubectl --help 這樣kubectl 有哪些用法就顯示出來, 我們要一級級的利用幫助 可能剛開始記住前面一個關鍵字,寫完關鍵字 help一下 又有很多詳細的用法
kubectl 命令規律總結
先看一組命令
kubectl delete sa metricbeat -n efk kubectl get sa --all-namespaces kubectl delete daemon-set metricbeat -n efk
-
1.會發現,kubectl 不管get 、delete describe等操作 后面跟資源類型 如果sa(serviceaccout) deployment pod,然后是資源名稱,如果沒有資源名稱,則刪除、獲取此類型所有的資源;最后限定某個命名空間,或者全部命名空間;這個限定命名空間 可以放在kubectl 后面,也可以放在所有參數后面; 也可以寫成資源類型/資源名稱;如
kubectl delete daemon-set/metricbeat -n efk
-
- -o 是指定輸出格式 輸出格式 說明 -o=custom-columns= 根據自定義列名進行輸出,以逗號分隔 -o=custom-colimns-file= 從文件中獲取自定義列名進行輸出 -o=json 以JSON格式顯示結果 -o=jsonpath=
如下:
kubectl get sa -n efk -o yaml kubectl get sa efk-elaticsearch -n efk -o yaml >xxx.yaml kubectl get pod efk-elaticsearch-0 -n efk -o wide
- 因為k8s 采用的是REST API接口,所有命令都最終會轉換成curl -X PUT POS等形式,為什么不直接使用curl命令,因為需要一堆相關授權,rancher UI里面 在deploy或其他資源中,選擇api查看 就可以查到,也可以點擊右側的edit編輯后 通過curl命令提交
API Request cURL command line: curl -u "${CATTLE_ACCESS_KEY}:${CATTLE_SECRET_KEY}" \ -X PUT \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ -d '{"annotations":{"cattle.io/timestamp":"", "cni.projectcalico.org/podIP":"10.42.1.44/32"}, "containers":[{"allowPrivilegeEscalation":false, "exitCode":null, "image":"172.16.35.31:1180/apm-images/gettoken:1.0", "imagePullPolicy":"IfNotPresent", "initContainer":false, "name":"genttoken", "ports":[{"containerPort":8001, "dnsName":"genttoken-nodeport", "kind":"NodePort", "name":"8001tcp301001", "protocol":"TCP", "sourcePort":30100, "type":"/v3/project/schemas/containerPort"}], "privileged":false, "procMount":"Default", "readOnly":false, "resources":{"type":"/v3/project/schemas/resourceRequirements"}, "restartCount":0, "runAsNonRoot":false, "state":"running", "stdin":true, "stdinOnce":false, "terminationMessagePath":"/dev/termination-log", "terminationMessagePolicy":" 等等
修改完成后 可以點擊send request來提交
k8s所有資源類型和別名(縮寫)
~]# 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 clusterauthtokens cluster.cattle.io true ClusterAuthToken clusteruserattributes cluster.cattle.io true ClusterUserAttribute leases coordination.k8s.io true Lease bgpconfigurations crd.projectcalico.org false BGPConfiguration clusterinformations crd.projectcalico.org false ClusterInformation felixconfigurations crd.projectcalico.org false FelixConfiguration globalnetworkpolicies crd.projectcalico.org false GlobalNetworkPolicy globalnetworksets crd.projectcalico.org false GlobalNetworkSet hostendpoints crd.projectcalico.org false HostEndpoint ippools crd.projectcalico.org false IPPool networkpolicies crd.projectcalico.org true NetworkPolicy events ev events.k8s.io true Event daemonsets ds extensions true DaemonSet deployments deploy extensions true Deployment ingresses ing extensions true Ingress networkpolicies netpol extensions true NetworkPolicy podsecuritypolicies psp extensions false PodSecurityPolicy replicasets rs extensions true ReplicaSet nodes metrics.k8s.io false NodeMetrics pods metrics.k8s.io true PodMetrics alertmanagers monitoring.coreos.com true Alertmanager prometheuses monitoring.coreos.com true Prometheus prometheusrules monitoring.coreos.com true PrometheusRule servicemonitors monitoring.coreos.com true ServiceMonitor networkpolicies netpol networking.k8s.io true NetworkPolicy 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 storageclasses sc storage.k8s.io false StorageClass volumeattachments storage.k8s.io false VolumeAttachment
k8s的資源類型,其中常用的資源一般有SHORTNAMES,在輸入命令時,輸入這種簡稱,無疑能提高效率。
kubectl get cs,要比kubectl get componentstatuses 書寫快的多,更容易記住。