k8s基础命令

k8s常见命令及参数

2.1 命令语法格式

kubectl特性丰富且功能强大,是kubernetes管理员最常用的集群管理工具,其最基本的语法格式如下:

kubectl [command] [TYPE] [NAME] [flages]

说明:

command:对资源执行相应操作的子命令,例如 get、create、delete、run 等;

TYPE:要操作的资源类型,例如pods、services等;类型名称大小写敏感,但支持使用单数、复数或简写格式;

NAME:要操作的资源对象名称,大小写敏感;省略时,则表示指定TYPE的所有资源对象;同一类型的资源名称可于TYPE后同时给出多个,也可以直接使用TYPE/NAME的格式来为每个资源对象分别指定类型;

flags:命令行选项,例如-s或--server等;另外get等命令在输出时还有一个常用的标志 -o <format> 用于指定输出格式

2.2 常见命令(command)

2.2.1 get

作用:显示一个或多个资源信息

例1:查看节点状态

[root@hostname /root] 

#kubectl get node

NAME                          STATUS  ROLES                                          AGE  VERSION

 "xx.xx.xx.xx"  Ready    worker  32d  v1.14.8-aliyun.1

 "xx.xx.xx.xx"  Ready    master,worker        32d  v1.14.8-aliyun.1

例2:查看velero命名空间(namespace)下的所有pod及svc资源

[root@ "xx.xx.xx.xx" /root] 

#kubectl get po,svc -n 命名空间

NAME                                              READY  STATUS    RESTARTS  AGE

pod/xx-xx-xxx-md58g                    2/2    Running  0          30d

pod/xxxx-xxx-4fwqc                      2/2    Running  0          30d

NAME                          TYPE        CLUSTER-IP    EXTERNAL-IP  PORT(S)            AGE

service/xx-svc   ClusterIP   "xx.xx.xx.xx"  <none>       xx/UDP,xx/TCP  33d

service/velero                ClusterIP   "xx.xx.xx.xx"    <none>            xx/TCP            33d

2.2.2 describe

作用:显示指定的资源或资源组的详细信息

例:查看kube-system命名空间下metrics-server这个pod的详细信息

第一步:根据ns及关键字获取到pod名称

[root@hostname /root] 

#kubectl get po -n 命名空间 | grep pod名称

pod名称                         1/1    Running    2          30d

第二步:查看describe信息

[root@hostname /root] 

#kubectl describe po -n 命名空间 pod名称

Events:

  Type    Reason    Age                    From                                  Message

  ----    ------    ----                  ----                                  -------

xxx

ps:在实际运维中,如遇pod状态异常,那首要任务就是查看pod describe中最下方Events字段中的信息

2.2.3 delete

作用:基于资源对象名称删除相关资源

例:删除ark-system命名空间下名为xxx的pod

[root@hostname /root] 

#kubectl delete po -n 命名空间 xxx

pod "xxx" deleted

2.2.4 edit

作用:编辑资源(执行命令后将会打开一个vim编辑器,操作同vim)

例:想要修改xxx ns下控制器名称的ds控制器中limit字段里memory的大小

第一步:编辑控制器

kubectl edit ds -n xxx 控制器名称

第二步:找到对应字段,修改完成保存退出

        resources:

          limits:

            cpu: 10m

            memory: 80Mi    ## 修改该字段的数值

          requests:

            cpu: 1m

            memory: 27996979200m

2.2.5 logs

作用:显示一个pod内容器的日志

例:查看 xxx.cloud.xx.amtest.xx 节点上rama-daemon组件的pod最后五行日志

第一步:根据节点hostname与pod名称关键词精确查找到podname

[root@hostname /root] 

#kubectl get pod -A -o wide | grep xxx.cloud.xx.amtestxx | grep rama-daemon

xxx              rama-xx-xx                                                 1/1    Running                316        33d     "xx.xx.xx.xx"     xxx.cloud.xx.amtestxx   <none>          <none>

第二步:查看pod日志

[root@hostname /root] 

#kubectl logs -n 命名空间 pod名称 --tail 5


补充:如果要查看容器上一次退出时候的日志,可以加上 -p 参数(previous)

kubectl logs -n 命名空间 pod名称 -p

2.2.6 apply

作用:基于文件或stdin将配置应用于资源

例:需将当前目录下名为job.yaml的文件创建为k8s资源

[root@hostname /root] 

#kubectl apply -f job.yaml

job.batch/xxx-xx created

2.2.7 exec

作用:对 Pod 中的容器执行命令

例1:进入default命名空间下 xxx pod,查看根下有哪些目录及文件

[root@hostname /root] 

#kubectl exec -it xxx bash

[root@xxx /home/admin/bin]

#ls /


例2:直接列出(不进入pod)default命名空间下 xxx pod 根下有哪些目录及文件

[root@hostname /root] 

#kubectl exec -it xxx -- ls /


2.2.8 (un)cordon

作用:(解除)限制节点调度pod

例1:设置节点为不可调度调度状态

kubectl cordon ${节点名}

例2:取消节点不可调度状态

kubectl uncordon ${节点名}

ps:当设置节点为cordon(不可调度)状态后,执行 kubectl get node 时候可以看到节点状态被标记为了 SchedulingDisabled

2.2.9 taint

作用:更新一个或多个节点上的污点

污点设置格式:kubectl taint node {nodename} {key}={value}:{effect}

例1:给节点 xxx.cloud.d02.amtestxx 添加污点 a=b:NoSchedule

[root@xxx.cloud.d02.amtestxx /root] 69E_OPS1

#kubectl taint node xxx.cloud.d02.amtestxx a=b:NoSchedule

node/xxx.cloud.d02.amtestxx tainted

例2:将节点 xxx.cloud.d02.amtestxx 上key为a的污点去除

[root@hostname /root] 

#kubectl taint node xxx.cloud.d02.amtestxx a-

node/xxx.cloud.d02.amtestxx untainted

例3:将节点 xxx.cloud.d02.amtestxx 上key为a的原有污点(a=b:NoSchedule)进行更新,更新后为(a=c:NoSchedule)

[root@hostname /root] 

#kubectl taint node xxx.amtest11 a=c:NoSchedule --overwrite

node/xxx.cloud.d02.amtestxx modified

2.2.10 label

作用:添加或更新一个或多个资源的标签

设置格式:kubectl label {TYPE} {key}={value}

例:给节点 xxx.cloud.d02.amtestxx 添加标签 a=b

[root@hostname /root] 

#kubectl label node xxx.cloud.d02.amtestxx a=b

node/xxx.cloud.d02.amtestxx labeled

去除标签、覆盖(overwrite)标签与taint操作方法基本一致故不再赘述

2.3 常见资源类型(TYPE)

2.3.1 原生资源类型

2.3.1.1 node

简介:Kubernetes 通过将容器放入在节点(Node)上运行的 Pod 中来执行你的工作负载

[root@hostname /root] 

#kubectl get node -o wide

2.3.1.2 pods

简介:Pod 是可以在 Kubernetes 中创建和管理的、最小的可部署的计算单元(可以由1个或多个容器组成)

[root@hostname /root] 

#kubectl get po -n 命名空间 -o wide

2.3.1.3 service

简介:Service 是将运行在一个或一组 Pod 上的网络应用程序公开为网络服务的方法

[root@hostname /root] 

#kubectl get service -n 命名空间


2.3.1.4 ingress

简介:Ingress 是对集群中服务的外部访问进行管理的 API 对象

[root@hostname /root] 

#kubectl get ing -n 命名空间

2.3.1.5 PersistentVolumeClaim(pvc)

简介:PersistentVolumeClaim 是用户针对一个持久卷的请求和申领

[root@hostname /root] 

#kubectl get pvc -n ark-system


2.3.1.6 PersistentVolume(pv)

简介:PersistentVolume 是管理员制备的一个存储资源

[root@hostname /root] 

#kubectl get pv

2.3.2 阿里专有云二次开发的资源类型

2.3.2.1 appset

简介:AppSets 是一组应用的定义, 即AppD 的列表, 对应一个产品Feature


2.3.2.2 appinstance

简介:AppInstance 是AppD 的运行态实例, 它记录了AppD chart 的parameterValues、resources、workload-Settings


2.3.2.3 ipinstance

简介:rama使用ipam为pod分配ip,每个被分配的ip使用ipinstance CR进行保存


2.3.2.4 subnet

简介:每个subnet 表示一个容器网段,


2.3.2.5 network

简介:network 表示一个pod 的调度域,属于特定network的pod,只能被调度到network指定的节点

[root@hostname /root] 

2.4 常见命令选项(flags

2.3.1 -A

作用:列出所有命名空间下的某个和多个资源

在专有云敏捷PaaS环境中由于k8s版本较低(1.12),故不支持 -A 选项,若需要查看所有ns下资源,可以使用 --all-namespaces;-A等价于 --all-namespaces

2.3.2 -o wide

作用:查看资源更多详细信息

示例:如果要查看某个pod ip及所调度的节点,仅使用 get pod 输出的结果是无法直接获取的,还需要加上 -o wide 选项才可以完整显示

[root@hostname /root] 

#kubectl get po xx

NAME              READY  STATUS    RESTARTS  AGE

xx   1/1    Running  0          38d

[root@hostname /root] 

#kubectl get po xx -o wide

NAME              READY  STATUS    RESTARTS  AGE  IP            NODE                          NOMINATED NODE  READINESS GATES

xx   1/1    Running  0          38d   xx.xx.xx.xx   xxx.cloud.d05.amtest11  <none>          <none>

2.3.3 -n

作用:namespace

ps:如果不指定 -n 则默认显示default命名空间下的资源,等价于 -n default

2.3.4 -o yaml

作用:指定结果输出结果显示格式以yaml格式输出

[root@hostname /root] 

#kubectl get svc kubernetes -o yaml

apiVersion: v1

kind: Service

metadata:

  creationTimestamp: "2023-03-28T03:22:20Z"

  labels:

    component: apiserver

    provider: kubernetes

  name: kubernetes

  namespace: default

  resourceVersion: "182"

  selfLink: /api/v1/namespaces/default/services/kubernetes

  uid: xxx-xx-xxx-xx

spec:

  clusterIP:  xx.xx.xx.xx

  ports:

  - name: https

    port: 443

    protocol: TCP

    targetPort: 6443

  sessionAffinity: None

  type: ClusterIP

status:

  loadBalancer: {}

2.3.5 -c

作用:指定pod中的容器名,可以是init容器,也可以是main容器

场景:当一个pod中包含多个容器时(非1/1)或者pod处于init0/1时需要查看日志时,直接执行 kubectl logs 是会报错的(如下图),会提示你需要指定其中一个容器查看日志,可以选择的容器列表在 [xxx] 中显示,例如nginx-ingress这个pod的中就包含2个主容器,分别为 nginx-ingress-controller 和 ingress-nginx-sidecar

如果需要查看其中一个容器日志就可以这样:

[root@hostname /root] 

#kubectl logs -n 命名空间 pod名称 -c 容器名称

2.3.6 -o json

作用:指定结果输出结果显示格式以json格式输出

[root@hostname /root] 

#kubectl get svc kubernetes -o json


2.4 k8s命令补齐与简写

2.4.1 命令补齐

说明:k8s命令简写是基于 bash-completion 这个包实现,在专有云PaaS底座中为默认安装,可以为简写相关k8s命令节省很多时间

使用方法:

例如你想输入 kubectl describe 这条命令,可以直接执行 kube <tab>  des<tab> 即可达到同样效果而不用一个个字母键入,工具会自动给你补齐,具体使用可自行去摸索体验

注意:如果kubectl做了alias(别名)则补全功能无法使用!必须使用kubectl的全写

2.4.2 命令简写

运维过程中很多命令我们可能无法清晰记得,比如 pvc 的全称为 persistentvolumeclaims 全部完整书写难度大且还不一定敲的正确,这时我们就可以使用该TYPE的简写成 pvc,省时省力又好记。在输入命令时候可以使用 kubectl api-resources 查看哪些命令支持缩写,在 SHORTNAMES 这一列对应的就是资源名的简写,例如:nodes 可以简写为 no,在执行命令的时候可以直接执行 kubectl get no 即可查看到节点列表及状态,等价于 kubectl get nodes

三、总结及小技巧

1.在查看pod资源信息时候请加上 -o wide 要不然看到节点/ip等信息我还得让你重新拍照

2.同一个命名空间(namespace)下的资源可以在一条命令同时操作,示例如下

kubectl delete po -n 命名空间 pod1 pod2 pod3

3.在删除sts类型的pod时,如果要同时删除该控制器下所属的全部pod,可以如下操作

[root@hostname /root] 

#kubectl get po -n 命名空间 | grep xxxx

xxxx-0                                      1/1    Running            0          37d

xxxx-1                                      1/1    Running            3          35d

xxxx-2                                      1/1    Running            0          37d

[root@hostname /root] 

#kubectl delete po -n 命名空间 xxxx-{0..2}

以上简单列举几个,更多快捷操作方法等你发现~

四、补充

3.1 kubectl支持的command有哪些?

kubectl支持的所有命令可以使用 kubectl --help 命令进行查看

[root@xxx.cloud.d02.amtestxx /root] 

#kubectl --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, Replication Controller, or Job

  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:

  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).

参考文档:命令行工具 (kubectl)· kubernetes docs

3.2 其他常用命令

限于篇幅原因,上面仅介绍了运维过程中最常用、最基础的操作命令,还要很多进阶命令需要学习和掌握,我哦再次列举几个,大家可以抽空进行学习和练习:

scale(伸缩Deployment、ReplicaSet、RC或job的规模)

cp(从容器中拷贝文件至宿主机或反之)

proxy(可以使kube-spiserver监听在本地的8001端口,进而直接访问apiserver无需配置token等步骤)

api-resources(可以查看k8s集群中所有的api资源信息)

version(打印kubernetes服务端和客户端的版本信息)

3.3 学习资料

本文仅涉及kubernetes核心基础操作命令,还远远不能满足k8s运维的需要,况且k8s版本迭代快;如果你想更深入的进阶学习k8s,欢迎参考学习以下链接及视频教程,希望对各位有所帮助:

1.kubernetes官方document(核心!学k8s不看官方Doc怎么行?)

https://kubernetes.io/zh-cn/docs/home/

2.kubernetes源码(适合会Go的大牛学习哦~新手略过)

https://github.com/kubernetes/kubernetes

3.尚硅谷 kubernetes教程(初学入门必备!

https://www.bilibili.com/video/BV1V5411j7Ui/?spm_id_from=333.337.search-card.all.click&vd_source=664cfb18ea327a9d839f13348f3534ed

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • kubectl run 所建立的是一个 deployment kubectl expose deployment ...
    万家千捣忙阅读 630评论 0 0
  • 文章是基于“Kubernetes权威指南”和博客[https://kuboard.cn/learning/]的学习...
    彦帧阅读 1,096评论 0 1
  • kubernetes 安装 [root@master ~]# curl -O ftp://172.100.0.11...
    renne阅读 243评论 0 0
  • 具体命令详解: 1.基础命令:https://www.jianshu.com/p/d2fe32fd46752.设置...
    小圆圈Belen阅读 2,976评论 0 1
  • 第一章k8s介绍 1.应用部署方式的演变 (1)传统部署方式 (2)虚拟化部署方式 (3)容器化部署 2.3个容器...
    玩转Linux与MySQL阅读 2,899评论 0 0