当前位置: 首页 > 工具软件 > kubectl-alias > 使用案例 >

kubernetes管理集群系列之命令行工具kubectl详解(二)

顾嘉纳
2023-12-01

前言:

一个k8s集群搭建完毕后,仅仅是万里长征的第一步,不管是以什么方式搭建的集群,比如,kubeadm或者二进制安装的,也不管是多master集群还是单master集群,不管是生产环境还是测试环境,集群搭建的目的都是为了使用这个集群。(集群搭建是比较基础的问题,在此不予讨论了)

k8s集群不同于其他的容器管理平台,比如,openstack,openstack可以有更多的管理选择比如api,但k8s使用最多也最频繁的是命令行工具kubectl。因此,kubectl能否正确使用,能否熟练使用将会影响到你对集群管理的效率。

正文:

一,

kubectl命令alias为 k

通常为了简化命令,我们可以使用alias命令将kubectl简化为k,本文后续将全部使用k代替kubectl。alias也非常简单。

[root@master ~]# whereis kubectl
kubectl: /usr/bin/kubectl
echo  "alias k=/usr/bin/kubectl">>/etc/profile
source /etc/profile

先查询出kubectl所在位置,然后将alias写入环境变量配置里,激活环境变量即可。

二,

kubectl的帮助

[root@master ~]# k --help
kubectl controls the Kubernetes cluster manager.

 Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/

Basic Commands (Beginner):
  create        Create a resource from a file or from stdin.
  expose        Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service
  run           Run a particular image on the cluster
  set           Set specific features on objects

Basic Commands (Intermediate):
  explain       Documentation of resources
  get           Display one or many resources
  edit          Edit a resource on the server
  delete        Delete resources by filenames, stdin, resources and names, or by resources and label selector

Deploy Commands:
  rollout       Manage the rollout of a resource
  scale         Set a new size for a Deployment, ReplicaSet or Replication Controller
  autoscale     Auto-scale a Deployment, ReplicaSet, or ReplicationController

Cluster Management Commands:
  certificate   Modify certificate resources.
  cluster-info  Display cluster info
  top           Display Resource (CPU/Memory/Storage) usage.
  cordon        Mark node as unschedulable
  uncordon      Mark node as schedulable
  drain         Drain node in preparation for maintenance
  taint         Update the taints on one or more nodes

Troubleshooting and Debugging Commands:
  describe      Show details of a specific resource or group of resources
  logs          Print the logs for a container in a pod
  attach        Attach to a running container
  exec          Execute a command in a container
  port-forward  Forward one or more local ports to a pod
  proxy         Run a proxy to the Kubernetes API server
  cp            Copy files and directories to and from containers.
  auth          Inspect authorization

Advanced Commands:
  diff          Diff live version against would-be applied version
  apply         Apply a configuration to a resource by filename or stdin
  patch         Update field(s) of a resource using strategic merge patch
  replace       Replace a resource by filename or stdin
  wait          Experimental: Wait for a specific condition on one or many resources.
  convert       Convert config files between different API versions
  kustomize     Build a kustomization target from a directory or a remote url.

Settings Commands:
  label         Update the labels on a resource
  annotate      Update the annotations on a resource
  completion    Output shell completion code for the specified shell (bash or zsh)

Other Commands:
  alpha         Commands for features in alpha
  api-resources Print the supported API resources on the server
  api-versions  Print the supported API versions on the server, in the form of "group/version"
  config        Modify kubeconfig files
  plugin        Provides utilities for interacting with plugins.
  version       Print the client and server version information

Usage:
  kubectl [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

很多同学看到某个命令茫茫多的参数,估计就菊花一紧,其实,不用慌,大部分都是不经常使用的,常用的也就那么几个参数。不过,从另一个方面来说,参数多,说明这个命令功能强大嘛,能干的事情非常多,也说明了k8s的复杂性。

这里要说一下,该命令帮助贴心的说明了有哪些部分,比如,
 

Basic Commands (Beginner)----------基础命令,最基础的命令, 这些命令应该全部掌握

Basic Commands (Intermediate)------------基础命令,中度使用命令,这些命令也应该全部掌握

Deploy Commands----------部署命令,这些命令需要掌握,autoscale除外

Cluster Management Commands---------集群管理命令,cluster-info,top,taint需要熟练掌握。

Troubleshooting and Debugging Commands---------debug和总结报告类型的命令 describe,logs,exec,port-forward,proxy需要熟练掌握

Advanced Commands------------高级进阶命令,apply,patch,replace,需要熟练掌握

Settings Commands----------------基本设置命令,label,annotate,completion需要熟练掌握

Other Commands--------------------其它类型的命令,api-resources,api-version,config,version,plugin需要熟练掌握

三,

k8s常用参数

  • Basic Commands (Beginner):
      create        Create a resource from a file or from stdin.
    

    这个是非常常用的参数,比如下面这个命令,将会快速的部署一个NGINX到集群内:

 

k create deployment nginx --image nginx:1.19

 此时查看pod,会发现是这样的:

kube-system   kube-scheduler-c7n.cnn                    1/1     Running             0          122m
[root@master ~]# k get pods -A
NAMESPACE     NAME                                      READY   STATUS              RESTARTS   AGE
database      mysql2-5db57c8bc8-7bwbg                   1/1     Running             3          3d18h
default       nfs-client-provisioner-6fc484bd4f-pjxm7   1/1     Running             2          2d23h
default       nginx-7b54d48599-x2zc5                    0/1     ContainerCreating   0          33s

containercreating表示正在拉取镜像,生成pod ,等待镜像拉取完成后,将端口暴露出来:

[root@master ~]# k expose deployment nginx --port 80 --type NodePort
service/nginx exposed

此时,将会有一个service建立,并且在集群外的机器上可以访问到这个pod了,30067就是刚才建立的pod暴露的端口号:

[root@master ~]# k get svc -A
NAMESPACE     NAME             TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)                  AGE
database      mysql2           NodePort    10.106.38.0     <none>        3306:32222/TCP           3d18h
default       kubernetes       ClusterIP   10.96.0.1       <none>        443/TCP                  27d
default       nginx            NodePort    10.96.201.101   <none>        80:30067/TCP             73s

此时,打开浏览器输入任意一个集群内所在机器的ip+端口号30067就可以访问到nginx的首页啦。 

 

  •  资源清单

k api-resources

[root@master ~]# k 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
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

这个命令是在Other Commands里面的,直接 kubectl  api-resources,这个非常重要,k8s的管理其实也主要是围绕着各种各样的资源来管理的。

第一列是所有k8s里的资源名称,常见的比如namespace,pods,nodes,StorageClass,service,statefulsets,deployments等等。

第二列是资源的缩写,比如,services=svc,pods=po,StorageClass=sc,PersistentVolumeClaim=pvc,PersistentVolume=pv等等。因此,比如查询所有namespaces有哪些,命令可以简化成这样:

[root@master ~]# k get ns 
NAME              STATUS   AGE
database          Active   3d23h
default           Active   27d
kube-node-lease   Active   27d
kube-public       Active   27d
kube-system       Active   27d

查询所有的pods,命令可以简化成这样:

[root@master ~]# k get po -A
NAMESPACE     NAME                                      READY   STATUS    RESTARTS   AGE
database      mysql2-5db57c8bc8-7bwbg                   1/1     Running   4          3d23h
default       nfs-client-provisioner-6fc484bd4f-pjxm7   1/1     Running   3          3d4h
default       nginx-7b54d48599-x2zc5                    1/1     Running   1          4h41m
default       test-pod                                  0/1     Pending   0          3d4h
kube-system   coredns-6c76c8bb89-tfcrm                  1/1     Running   5          27d
kube-system   coredns-6c76c8bb89-vnlwg                  1/1     Running   5          27d
kube-system   etcd-c7n.cnn                              1/1     Running   6          27d
kube-system   kube-apiserver-c7n.cnn                    1/1     Running   5          3d21h
kube-system   kube-controller-manager-c7n.cnn           1/1     Running   2          6h49m
kube-system   kube-flannel-ds-djwmq                     1/1     Running   4          4d
kube-system   kube-flannel-ds-f5gtd                     1/1     Running   5          4d
kube-system   kube-flannel-ds-k5jpf                     1/1     Running   4          4d
kube-system   kube-proxy-7v5mj                          1/1     Running   5          27d
kube-system   kube-proxy-mtttm                          1/1     Running   5          27d
kube-system   kube-proxy-zwmwf                          1/1     Running   6          27d
kube-system   kube-scheduler-c7n.cnn                    1/1     Running   1          6h44m

 

第三例是资源的apigroup,比如编写jobs相关的资源清单文件,apiversion就必须是batch这个apigroup啦,当然,/ 后面还需要通过 k api-versions 这个命令查询。

比如这个定时任务资源清单文件:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            args:
            - /bin/sh
            - -c
            - date; echo Hello world!!!!!!!
          restartPolicy: OnFailure

第四列是资源是否必须和namespace关联,比如,nodes就不能通过namespace隔离,但pods可以通过namespace隔离,假如有两个不同的namespace A和Bnamespace,k8s会认为 A中运行的nginx-1.20.1和B中运行的nginx-1.20.1是两个不同的pod,并且在定义或者使用这些资源的时候,如果该列为true值,那么,必须要指定namespace,否则使用default这个namespace,如果该列为false值,那么,在定义资源的时候不需要指定namespace。

第五列是资源定义的时候kind的值,比如,要定义一个jobs资源,kind的值必须是Job(注意,这里是区分大小写的哦,切记!!!!!!),上面示例的第二行cronjob对应的kind的值就必须是CronJob 。

  • 版本清单

k api-versions,通过此命令可查询出现有的k8s集群所支持的kind版本。上面那个cronjob文件为例,可以知道,我这个集群,资源清单文件首行可以写成:apiVersion: batch/v1beta1  也可以写成apiVersion: batch/v1  这样的形式,在这个集群内都是OK的。

[root@master ~]# k api-versions
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
discovery.k8s.io/v1beta1
events.k8s.io/v1
events.k8s.io/v1beta1
extensions/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
  • Basic Commands (Intermediate)里的get参数

kubectl命令里的get参数是使用频率最高的,没有之一,kubectl get --help  是该参数的详细介绍:

[root@master ~]# k get --help
Display one or many resources

 Prints a table of the most important information about the specified resources. You can filter the list using a label
selector and the --selector flag. If the desired resource type is namespaced you will only see results in your current
namespace unless you pass --all-namespaces.

 Uninitialized objects are not shown unless --include-uninitialized is passed.

 By specifying the output as 'template' and providing a Go template as the value of the --template flag, you can filter
the attributes of the fetched resources.

Use "kubectl api-resources" for a complete list of supported resources.

Examples:
  # List all pods in ps output format.
  kubectl get pods
  
  # List all pods in ps output format with more information (such as node name).
  kubectl get pods -o wide
  
  # List a single replication controller with specified NAME in ps output format.
  kubectl get replicationcontroller web
  
  # List deployments in JSON output format, in the "v1" version of the "apps" API group:
  kubectl get deployments.v1.apps -o json
  
  # List a single pod in JSON output format.
  kubectl get -o json pod web-pod-13je7
  
  # List a pod identified by type and name specified in "pod.yaml" in JSON output format.
  kubectl get -f pod.yaml -o json
  
  # List resources from a directory with kustomization.yaml - e.g. dir/kustomization.yaml.
  kubectl get -k dir/
  
  # Return only the phase value of the specified pod.
  kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}
  
  # List resource information in custom columns.
  kubectl get pod test-pod -o custom-columns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image
  
  # List all replication controllers and services together in ps output format.
  kubectl get rc,services
  
  # List one or more resources by their type and names.
  kubectl get rc/web service/frontend pods/web-pod-13je7

Options:
  -A, --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current
context is ignored even if specified with --namespace.
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --chunk-size=500: Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and
may change in the future.
      --field-selector='': Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector
key1=value1,key2=value2). The server only supports a limited number of field queries per type.
  -f, --filename=[]: Filename, directory, or URL to files identifying the resource to get from a server.
      --ignore-not-found=false: If the requested object does not exist the command will return exit code 0.
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
  -L, --label-columns=[]: Accepts a comma separated list of labels that are going to be presented as columns. Names are
case-sensitive. You can also use multiple flag options like -L label1 -L label2...
      --no-headers=false: When using the default or custom-column output format, don't print headers (default print
headers).
  -o, --output='': Output format. One of:
json|yaml|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...
See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template
[http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template
[http://kubernetes.io/docs/user-guide/jsonpath].
      --output-watch-events=false: Output watch event objects when --watch or --watch-only is used. Existing objects are
output as initial ADDED events.
      --raw='': Raw URI to request from the server.  Uses the transport specified by the kubeconfig file.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
  -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
      --server-print=true: If true, have the server return the appropriate table output. Supports extension APIs and
CRDs.
      --show-kind=false: If present, list the resource type for the requested object(s).
      --show-labels=false: When printing, show all labels as the last column (default hide labels column)
      --sort-by='': If non-empty, sort list types using this field specification.  The field specification is expressed
as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression
must be an integer or a string.
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
  -w, --watch=false: After listing/getting the requested object, watch for changes. Uninitialized objects are excluded
if no object name is provided.
      --watch-only=false: Watch for changes to the requested object(s), without listing/getting first.

Usage:
  kubectl get
[(-o|--output=)json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...]
(TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags] [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

该帮助给出了一些例子,总的来说,k get  resource 名称即可,例如:

副本控制器 replicationcontrollers

[root@master ~]# k get rs -A
NAMESPACE     NAME                                DESIRED   CURRENT   READY   AGE
database      mysql2-5db57c8bc8                   1         1         1       4d
default       nfs-client-provisioner-556768d99f   0         0         0       4d1h
default       nfs-client-provisioner-5bd5bb49f    0         0         0       4d
default       nfs-client-provisioner-5c786944fc   0         0         0       4d1h
default       nfs-client-provisioner-6fc484bd4f   1         1         1       3d5h
default       nfs-client-provisioner-75ffb44498   0         0         0       4d
default       nfs-client-provisioner-7d8bb64cc    0         0         0       3d23h
default       nfs-client-provisioner-d7d7f8859    0         0         0       3d23h
default       nginx-7b54d48599                    1         1         1       5h48m
kube-system   coredns-6c76c8bb89                  2         2         2       27d

例如查询集群内所有角色:

[root@master ~]# k get clusterroles -A
NAME                                                                   CREATED AT
admin                                                                  2022-06-13T02:56:43Z
cluster-admin                                                          2022-06-13T02:56:43Z
edit                                                                   2022-06-13T02:56:43Z
flannel                                                                2022-07-06T08:07:44Z
kubeadm:get-nodes                                                      2022-06-13T02:56:45Z
nfs-provisioner-runner                                                 2022-07-06T08:09:42Z
system:aggregate-to-admin                                              2022-06-13T02:56:43Z
system:aggregate-to-edit                                               2022-06-13T02:56:43Z
system:aggregate-to-view                                               2022-06-13T02:56:43Z
system:auth-delegator                                                  2022-06-13T02:56:43Z
system:basic-user                                                      2022-06-13T02:56:43Z
system:certificates.k8s.io:certificatesigningrequests:nodeclient       2022-06-13T02:56:43Z
system:certificates.k8s.io:certificatesigningrequests:selfnodeclient   2022-06-13T02:56:43Z
system:certificates.k8s.io:kube-apiserver-client-approver              2022-06-13T02:56:43Z
system:certificates.k8s.io:kube-apiserver-client-kubelet-approver      2022-06-13T02:56:43Z
system:certificates.k8s.io:kubelet-serving-approver                    2022-06-13T02:56:43Z
system:certificates.k8s.io:legacy-unknown-approver                     2022-06-13T02:56:43Z
system:controller:attachdetach-controller                              2022-06-13T02:56:43Z
system:controller:certificate-controller                               2022-06-13T02:56:44Z
system:controller:clusterrole-aggregation-controller                   2022-06-13T02:56:43Z
system:controller:cronjob-controller                                   2022-06-13T02:56:43Z
system:controller:daemon-set-controller                                2022-06-13T02:56:44Z
system:controller:deployment-controller                                2022-06-13T02:56:44Z
system:controller:disruption-controller                                2022-06-13T02:56:44Z
system:controller:endpoint-controller                                  2022-06-13T02:56:44Z
system:controller:endpointslice-controller                             2022-06-13T02:56:44Z
system:controller:endpointslicemirroring-controller                    2022-06-13T02:56:44Z
system:controller:expand-controller                                    2022-06-13T02:56:44Z
system:controller:generic-garbage-collector                            2022-06-13T02:56:44Z
system:controller:horizontal-pod-autoscaler                            2022-06-13T02:56:44Z
system:controller:job-controller                                       2022-06-13T02:56:44Z
system:controller:namespace-controller                                 2022-06-13T02:56:44Z
system:controller:node-controller                                      2022-06-13T02:56:44Z
system:controller:persistent-volume-binder                             2022-06-13T02:56:44Z
system:controller:pod-garbage-collector                                2022-06-13T02:56:44Z
system:controller:pv-protection-controller                             2022-06-13T02:56:44Z
system:controller:pvc-protection-controller                            2022-06-13T02:56:44Z
system:controller:replicaset-controller                                2022-06-13T02:56:44Z
system:controller:replication-controller                               2022-06-13T02:56:44Z
system:controller:resourcequota-controller                             2022-06-13T02:56:44Z
system:controller:route-controller                                     2022-06-13T02:56:44Z
system:controller:service-account-controller                           2022-06-13T02:56:44Z
system:controller:service-controller                                   2022-06-13T02:56:44Z
system:controller:statefulset-controller                               2022-06-13T02:56:44Z
system:controller:ttl-controller                                       2022-06-13T02:56:44Z
system:coredns                                                         2022-06-13T02:56:45Z
system:discovery                                                       2022-06-13T02:56:43Z
system:heapster                                                        2022-06-13T02:56:43Z
system:kube-aggregator                                                 2022-06-13T02:56:43Z
system:kube-controller-manager                                         2022-06-13T02:56:43Z
system:kube-dns                                                        2022-06-13T02:56:43Z
system:kube-scheduler                                                  2022-06-13T02:56:43Z
system:kubelet-api-admin                                               2022-06-13T02:56:43Z
system:node                                                            2022-06-13T02:56:43Z
system:node-bootstrapper                                               2022-06-13T02:56:43Z
system:node-problem-detector                                           2022-06-13T02:56:43Z
system:node-proxier                                                    2022-06-13T02:56:43Z
system:persistent-volume-provisioner                                   2022-06-13T02:56:43Z
system:public-info-viewer                                              2022-06-13T02:56:43Z
system:volume-scheduler                                                2022-06-13T02:56:43Z
view                                                                   2022-06-13T02:56:43Z

 查询角色绑定情况:

[root@master ~]# k get rolebindings -A
NAMESPACE     NAME                                                ROLE                                                  AGE
kube-public   kubeadm:bootstrap-signer-clusterinfo                Role/kubeadm:bootstrap-signer-clusterinfo             27d
kube-public   system:controller:bootstrap-signer                  Role/system:controller:bootstrap-signer               27d
kube-system   kube-proxy                                          Role/kube-proxy                                       27d
kube-system   kubeadm:kubelet-config-1.19                         Role/kubeadm:kubelet-config-1.19                      27d
kube-system   kubeadm:nodes-kubeadm-config                        Role/kubeadm:nodes-kubeadm-config                     27d
kube-system   system::extension-apiserver-authentication-reader   Role/extension-apiserver-authentication-reader        27d
kube-system   system::leader-locking-kube-controller-manager      Role/system::leader-locking-kube-controller-manager   27d
kube-system   system::leader-locking-kube-scheduler               Role/system::leader-locking-kube-scheduler            27d
kube-system   system:controller:bootstrap-signer                  Role/system:controller:bootstrap-signer               27d
kube-system   system:controller:cloud-provider                    Role/system:controller:cloud-provider                 27d
kube-system   system:controller:token-cleaner                     Role/system:controller:token-cleaner                  27d

这里注意一点,查询所有 后面加个 -A 或者--all 都可以的哦:

[root@master ~]# k get rolebindings -A
NAMESPACE     NAME                                                ROLE                                                  AGE
kube-public   kubeadm:bootstrap-signer-clusterinfo                Role/kubeadm:bootstrap-signer-clusterinfo             27d
kube-public   system:controller:bootstrap-signer                  Role/system:controller:bootstrap-signer               27d
kube-system   kube-proxy                                          Role/kube-proxy                                       27d
kube-system   kubeadm:kubelet-config-1.19                         Role/kubeadm:kubelet-config-1.19                      27d
kube-system   kubeadm:nodes-kubeadm-config                        Role/kubeadm:nodes-kubeadm-config                     27d
kube-system   system::extension-apiserver-authentication-reader   Role/extension-apiserver-authentication-reader        27d
kube-system   system::leader-locking-kube-controller-manager      Role/system::leader-locking-kube-controller-manager   27d
kube-system   system::leader-locking-kube-scheduler               Role/system::leader-locking-kube-scheduler            27d
kube-system   system:controller:bootstrap-signer                  Role/system:controller:bootstrap-signer               27d
kube-system   system:controller:cloud-provider                    Role/system:controller:cloud-provider                 27d
kube-system   system:controller:token-cleaner                     Role/system:controller:token-cleaner                  27d

官方的帮助文档其实已经非常详细了,在此我就抛砖引玉一下,只需要记住,k get resource名称 -A ,如果该资源有,那么就可以查询到,如果没有,它也会提示的哦,在比如,集群报错信息:

[root@master ~]# k get events -A
NAMESPACE   LAST SEEN   TYPE      REASON                 OBJECT                             MESSAGE
default     8s          Normal    ExternalProvisioning   persistentvolumeclaim/test-claim   waiting for a volume to be created, either by external provisioner "fuseim.pri/ifs" or manually created by system administrator
default     11m         Warning   FailedScheduling       pod/test-pod                       0/3 nodes are available: 3 pod has unbound immediate PersistentVolumeClaims.

 根据以上提示,在查询pvc,可以看到现在有pvc状态是不对的:

[root@master ~]# k get pvc -A
NAMESPACE   NAME           STATUS    VOLUME         CAPACITY   ACCESS MODES   STORAGECLASS          AGE
database    nfs-pvc-test   Bound     nfs-pv-test1   1536Mi     RWO            nfs                   4d
default     test-claim     Pending                                            managed-nfs-storage   3d5h
  • Troubleshooting and Debugging Commands里的describe和logs参数 

describe和logs是在集群的使用过程中,各种各样的资源有可能会出现问题,此时,debug追踪查看问题原因时使用,也是使用非常多的参数

例如,k describe --help的帮助:

[root@master ~]# k describe --help
Show details of a specific resource or group of resources

 Print a detailed description of the selected resources, including related resources such as events or controllers. You
may select a single object by name, all objects of that type, provide a name prefix, or label selector. For example:

  $ kubectl describe TYPE NAME_PREFIX
  
 will first check for an exact match on TYPE and NAME_PREFIX. If no such resource exists, it will output details for
every resource that has a name prefixed with NAME_PREFIX.

Use "kubectl api-resources" for a complete list of supported resources.

Examples:
  # Describe a node
  kubectl describe nodes kubernetes-node-emt8.c.myproject.internal
  
  # Describe a pod
  kubectl describe pods/nginx
  
  # Describe a pod identified by type and name in "pod.json"
  kubectl describe -f pod.json
  
  # Describe all pods
  kubectl describe pods
  
  # Describe pods by label name=myLabel
  kubectl describe po -l name=myLabel
  
  # Describe all pods managed by the 'frontend' replication controller (rc-created pods
  # get the name of the rc as a prefix in the pod the name).
  kubectl describe pods frontend

Options:
  -A, --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current
context is ignored even if specified with --namespace.
  -f, --filename=[]: Filename, directory, or URL to files containing the resource to describe
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
  -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
      --show-events=true: If true, display events related to the described object.

Usage:
  kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME) [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

同样的,该参数也有详细的说明并且有一些简单的示例,例如查询本集群的slave1节点的详细信息:

[root@master ~]# k describe nodes slave1
Name:               slave1
Roles:              <none>
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/arch=amd64
                    kubernetes.io/hostname=slave1
                    kubernetes.io/os=linux
Annotations:        flannel.alpha.coreos.com/backend-data: {"VtepMAC":"52:04:85:12:ca:e2"}
                    flannel.alpha.coreos.com/backend-type: vxlan
                    flannel.alpha.coreos.com/kube-subnet-manager: true
                    flannel.alpha.coreos.com/public-ip: 192.168.217.17
                    kubeadm.alpha.kubernetes.io/cri-socket: /var/run/dockershim.sock
                    node.alpha.kubernetes.io/ttl: 0
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Mon, 13 Jun 2022 10:57:25 +0800
Taints:             <none>
Unschedulable:      false
Lease:
  HolderIdentity:  slave1
  AcquireTime:     <unset>
  RenewTime:       Sun, 10 Jul 2022 17:42:22 +0800
Conditions:
  Type                 Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----                 ------  -----------------                 ------------------                ------                       -------
  NetworkUnavailable   False   Sun, 10 Jul 2022 15:52:41 +0800   Sun, 10 Jul 2022 15:52:41 +0800   FlannelIsUp                  Flannel is running on this node
  MemoryPressure       False   Sun, 10 Jul 2022 17:38:35 +0800   Mon, 13 Jun 2022 10:57:26 +0800   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure         False   Sun, 10 Jul 2022 17:38:35 +0800   Mon, 13 Jun 2022 10:57:26 +0800   KubeletHasNoDiskPressure     kubelet has no disk pressure
  PIDPressure          False   Sun, 10 Jul 2022 17:38:35 +0800   Mon, 13 Jun 2022 10:57:26 +0800   KubeletHasSufficientPID      kubelet has sufficient PID available
  Ready                True    Sun, 10 Jul 2022 17:38:35 +0800   Mon, 13 Jun 2022 10:57:36 +0800   KubeletReady                 kubelet is posting ready status
Addresses:
  InternalIP:  192.168.217.17
  Hostname:    slave1
Capacity:
  cpu:                8
  ephemeral-storage:  10230Mi
  hugepages-2Mi:      0
  memory:             4026340Ki
  pods:               110
Allocatable:
  cpu:                8
  ephemeral-storage:  9654239217
  hugepages-2Mi:      0
  memory:             3923940Ki
  pods:               110
System Info:
  Machine ID:                 9e1e6e06c15e4e43a32b308f9e7106fa
  System UUID:                2ed24d56-5e02-0ef6-f3fc-b3acc3e99e89
  Boot ID:                    6e80cbd7-8f7d-46cc-9458-cb040dbf3206
  Kernel Version:             5.16.9-1.el7.elrepo.x86_64
  OS Image:                   CentOS Linux 7 (Core)
  Operating System:           linux
  Architecture:               amd64
  Container Runtime Version:  docker://20.10.7
  Kubelet Version:            v1.19.4
  Kube-Proxy Version:         v1.19.4
PodCIDR:                      10.244.1.0/24
PodCIDRs:                     10.244.1.0/24
Non-terminated Pods:          (5 in total)
  Namespace                   Name                        CPU Requests  CPU Limits  Memory Requests  Memory Limits  AGE
  ---------                   ----                        ------------  ----------  ---------------  -------------  ---
  database                    mysql2-5db57c8bc8-7bwbg     0 (0%)        0 (0%)      0 (0%)           0 (0%)         4d
  default                     nginx-7b54d48599-x2zc5      0 (0%)        0 (0%)      0 (0%)           0 (0%)         6h9m
  kube-system                 coredns-6c76c8bb89-tfcrm    100m (1%)     0 (0%)      70Mi (1%)        170Mi (4%)     27d
  kube-system                 kube-flannel-ds-djwmq       100m (1%)     100m (1%)   50Mi (1%)        50Mi (1%)      4d1h
  kube-system                 kube-proxy-mtttm            0 (0%)        0 (0%)      0 (0%)           0 (0%)         27d
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests    Limits
  --------           --------    ------
  cpu                200m (2%)   100m (1%)
  memory             120Mi (3%)  220Mi (5%)
  ephemeral-storage  0 (0%)      0 (0%)
  hugepages-2Mi      0 (0%)      0 (0%)
Events:              <none>

该节点的非常详细的信息都查询出来了,比如,运行了哪些pod,当然,我们也可以使用组合命令来查询slave1到底有运行哪些pod,但是,describe是把非常多的信息都给列出来了啊:

[root@master ~]# k get pods -A -o wide |grep slave1
database      mysql2-5db57c8bc8-7bwbg                   1/1     Running   4          4d      10.244.1.14      slave1    <none>           <none>
default       nginx-7b54d48599-x2zc5                    1/1     Running   1          6h12m   10.244.1.12      slave1    <none>           <none>
kube-system   coredns-6c76c8bb89-tfcrm                  1/1     Running   5          27d     10.244.1.13      slave1    <none>           <none>
kube-system   kube-flannel-ds-djwmq                     1/1     Running   4          4d1h    192.168.217.17   slave1    <none>           <none>
kube-system   kube-proxy-mtttm                          1/1     Running   5          27d     192.168.217.17   slave1    <none>           <none>

两个命令可以互相印证的哦,k describe node slave1  里关于slave1里有哪些pods和  k get pods -A -o wide |grep slave1 结果是一致的哦。

还有一些别的参数,比如logs,apply等等参数,都可以通过--help查询出来具体的用法,在此就不献丑了。

总结

kubectl 命令参数非常多,但常用的应该也就十来个吧,大体上是有这样一些常用参数:

describe,get,apply,taint,create,run,logs,delete,api-version,version,api-resources,rollout,scale,edit,expose,replace

如有遗漏,欢迎补充哦

 类似资料: