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

简介: kubernetes管理集群系列之命令行工具kubectl详解

前言:


一个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 。


相关实践学习
深入解析Docker容器化技术
Docker是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的Linux机器上,也可以实现虚拟化,容器是完全使用沙箱机制,相互之间不会有任何接口。Docker是世界领先的软件容器平台。开发人员利用Docker可以消除协作编码时“在我的机器上可正常工作”的问题。运维人员利用Docker可以在隔离容器中并行运行和管理应用,获得更好的计算密度。企业利用Docker可以构建敏捷的软件交付管道,以更快的速度、更高的安全性和可靠的信誉为Linux和Windows Server应用发布新功能。 在本套课程中,我们将全面的讲解Docker技术栈,从环境安装到容器、镜像操作以及生产环境如何部署开发的微服务应用。本课程由黑马程序员提供。 &nbsp; &nbsp; 相关的阿里云产品:容器服务 ACK 容器服务 Kubernetes 版(简称 ACK)提供高性能可伸缩的容器应用管理能力,支持企业级容器化应用的全生命周期管理。整合阿里云虚拟化、存储、网络和安全能力,打造云端最佳容器化应用运行环境。 了解产品详情: https://www.aliyun.com/product/kubernetes
目录
相关文章
|
3月前
|
人工智能 算法 调度
阿里云ACK托管集群Pro版共享GPU调度操作指南
本文介绍在阿里云ACK托管集群Pro版中,如何通过共享GPU调度实现显存与算力的精细化分配,涵盖前提条件、使用限制、节点池配置及任务部署全流程,提升GPU资源利用率,适用于AI训练与推理场景。
332 1
|
3月前
|
弹性计算 监控 调度
ACK One 注册集群云端节点池升级:IDC 集群一键接入云端 GPU 算力,接入效率提升 80%
ACK One注册集群节点池实现“一键接入”,免去手动编写脚本与GPU驱动安装,支持自动扩缩容与多场景调度,大幅提升K8s集群管理效率。
267 89
|
8月前
|
资源调度 Kubernetes 调度
从单集群到多集群的快速无损转型:ACK One 多集群应用分发
ACK One 的多集群应用分发,可以最小成本地结合您已有的单集群 CD 系统,无需对原先应用资源 YAML 进行修改,即可快速构建成多集群的 CD 系统,并同时获得强大的多集群资源调度和分发的能力。
334 9
|
8月前
|
资源调度 Kubernetes 调度
从单集群到多集群的快速无损转型:ACK One 多集群应用分发
本文介绍如何利用阿里云的分布式云容器平台ACK One的多集群应用分发功能,结合云效CD能力,快速将单集群CD系统升级为多集群CD系统。通过增加分发策略(PropagationPolicy)和差异化策略(OverridePolicy),并修改单集群kubeconfig为舰队kubeconfig,可实现无损改造。该方案具备多地域多集群智能资源调度、重调度及故障迁移等能力,帮助用户提升业务效率与可靠性。
|
10月前
|
存储 Kubernetes 监控
K8s集群实战:使用kubeadm和kuboard部署Kubernetes集群
总之,使用kubeadm和kuboard部署K8s集群就像回归童年一样,简单又有趣。不要忘记,技术是为人服务的,用K8s集群操控云端资源,我们不过是想在复杂的世界找寻简单。尽管部署过程可能遇到困难,但朝着简化复杂的目标,我们就能找到意义和乐趣。希望你也能利用这些工具,找到你的乐趣,满足你的需求。
930 33
|
10月前
|
Kubernetes 开发者 Docker
集群部署:使用Rancher部署Kubernetes集群。
以上就是使用 Rancher 部署 Kubernetes 集群的流程。使用 Rancher 和 Kubernetes,开发者可以受益于灵活性和可扩展性,允许他们在多种环境中运行多种应用,同时利用自动化工具使工作负载更加高效。
547 19
|
10月前
|
人工智能 分布式计算 调度
打破资源边界、告别资源浪费:ACK One 多集群Spark和AI作业调度
ACK One多集群Spark作业调度,可以帮助您在不影响集群中正在运行的在线业务的前提下,打破资源边界,根据各集群实际剩余资源来进行调度,最大化您多集群中闲置资源的利用率。
|
10月前
|
Kubernetes API 网络安全
当node节点kubectl 命令无法连接到 Kubernetes API 服务器
当Node节点上的 `kubectl`无法连接到Kubernetes API服务器时,可以通过以上步骤逐步排查和解决问题。首先确保网络连接正常,验证 `kubeconfig`文件配置正确,检查API服务器和Node节点的状态,最后排除防火墙或网络策略的干扰,并通过重启服务恢复正常连接。通过这些措施,可以有效解决与Kubernetes API服务器通信的常见问题,从而保障集群的正常运行。
776 17
|
10月前
|
Prometheus Kubernetes 监控
OpenAI故障复盘丨如何保障大规模K8s集群稳定性
OpenAI故障复盘丨如何保障大规模K8s集群稳定性
381 0
OpenAI故障复盘丨如何保障大规模K8s集群稳定性
|
11月前
|
运维 分布式计算 Kubernetes
ACK One多集群Service帮助大批量应用跨集群无缝迁移
ACK One多集群Service可以帮助您,在无需关注服务间的依赖,和最小化迁移风险的前提下,完成跨集群无缝迁移大批量应用。

推荐镜像

更多