kubernetes 敏感位置配置数据(第3课Kubectl常用命令详解)

摘要

本文介绍k8s集群管理命令Kubectl分类和命令详解。

内容(1)Kubectl常用子命令分类

kubernetes 敏感位置配置数据(第3课Kubectl常用命令详解)(1)

(2)语法

$ kubectl [command] [TYPE] [NAME] [flags]

command:子命令 TYPE:资源类型 NAME:资源名称 flags:命令参数

  • 命令帮助 kubectl命令的帮助很详细,kubectl -h会列出所有的子命令,在任何子命令后跟 -h,都会输出详细的帮助以及用例,遇到问题可以随时查看帮助。
  • 资源对象 kubectl大部分子命令后都可以指定要操作的资源对象,可以用kubectl api-resources命令参考
  • 全局参数 kubectl options命令可以列出可以全局使用的命令参数,比较重要的有:

--Cluster='': 指定命令操作对象的集群 --context='': 指定命令操作对象的上下文 -n, --namespace='': 指定命令操作对象的Namespace

  • 资源字段 kubectl explain命令可以输出资源对应的属性字段及定义,在定义资源配置文件时候非常有用。

# Usage: kubectl explain RESOURCE [options] # Examples: $ kubectl explain deployment.spec.selector KIND: Deployment VERSION: extensions/v1beta1 RESOURCE: selector <Object> DESCRIPTION: Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment. A label selector is a label query over a set of resources. The result of matchLabels and matchExpressions are ANDed. An empty label selector matches all objects. A null label selector matches no objects. FIELDS: matchExpressions <[]Object> matchExpressions is a list of label selector requirements. The requirements are ANDed. matchLabels <map[string]string> matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed.

(3)声明式资源对象管理

对集群资源的声明式管理,是kubernetes最主要的特性之一,而kubectl apply命令是最能体现这个特性的命令。apply命令最主要的参数有两个:

# Usage: kubectl apply (-f FILENAME | -k DIRECTORY) [options]

-f 参数后跟yaml或json格式的资源配置文件,-k 参数后跟kustomization.yaml配置文件的位置。

为什么说apply是声明式管理呢,因为所有对集群的增改操作,都能用apply命令完成,一切取决于后面的配置文件:

如果配置文件中的资源找集群中不存在,则创建这个资源。 如果配置文件中的资源在集群中已存在,则根据配置对资源字段进行更新

举个例子:

# 部署一个goweb应用,配置pod数为4个: [root@master-1 ~]# grep replicas deployment-goweb.yaml replicas: 4 # 使用 apply 创建资源 [root@master-1 ~]# kubectl apply -f deployment-goweb.yaml deployment.apps/goweb created [root@master-1 ~]# kubectl get Pods NAME READY STATUS RESTARTS AGE goweb-6b5d559869-4x5mb 1/1 Running 0 14s goweb-6b5d559869-77lbz 1/1 Running 0 14s goweb-6b5d559869-9ztkh 1/1 Running 0 14s goweb-6b5d559869-ccjtp 1/1 Running 0 14s # 修改pod数量为2个: [root@master-1 ~]# sed -ri 's/4$/2/g' deployment-goweb.yaml [root@master-1 ~]# grep replicas deployment-goweb.yaml replicas: 2 # 使用apply更新资源 [root@master-1 ~]# kubectl apply -f deployment-goweb.yaml deployment.apps/goweb configured [root@master-1 ~]# kubectl get pods NAME READY STATUS REStarTS AGE goweb-6b5d559869-4x5mb 1/1 Running 0 8m21s goweb-6b5d559869-77lbz 1/1 Running 0 8m21s # pod数已更新为2个

可以看到,同一个kubectl apply -f deployment-goweb.yaml命令,可以用来创建资源也可以更新资源。 简单来说,apply命令的作用就是一个:使集群的实际状态朝用户声明的期望状态变化,而用户不用关心具体要进行怎样的增删改操作才能呢达到这个期望状态,也即Kubernetes的声明式资源管理。

(4)命令式资源对象管理

命令式管理类就是直接通过命令执行增删改的操作,除了删除资源外,下面的命令能用apply代替,kubernetes也建议尽量使用apply命令。

  • 创建资源kubectl create deployment my-dep --image=busybox # 创建一个deplpymementkubectl expose rc nginx --port=80 --target-port=8000 # 创建一个svc,暴露nginx这个rc
  • 更新资源kubectl scale --replicas=3 -f foo.yaml # 将foo.yaml中描述的对象扩展为3个kubectl annotate pods foo description='my frontend' # 增加description='my frontend'备注,已有保留不覆盖kubectl label --overwrite pods foo status=unhealthy # 增加status=unhealthy 标签,已有则覆盖
  • 删除资源

kubectl delete -f xxx.yaml # 删除一个配置文件对应的资源对象 kubectl delete pod,service baz foo # 删除名字为baz或foo的pod和service kubectl delete pods,services -l name=myLabel # -l 参数可以删除包含指定label的资源对象 kubectl delete pod foo --grace-period=0 --force # 强制删除一个pod,在各种原因pod一直terminate不掉的时候很有用

(5)查看资源状态
  • get 最常用的查看命令,显示一个或多个资源的详细信息

# Usage: kubectl get [(-o|--output=)](TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags] [options] # Examples: kubectl get services # 列出当前NS中所有service资源 kubectl get pods --all-namespaces # 列出集群所有NS中所有的Pod kubectl get pods -o wide # -o wide也比较常用,可以显示更多资源信息,比如pod的IP等 kubectl get deployment my-dep # 可以直接指定资源名查看 kubectl get deployment my-dep --watch # --watch 参数可以监控资源的状态,在状态变换时输出。在跟踪服务部署情况时很有用 kubectl get pod my-pod -o yaml # 查看yaml格式的资源配置,这里包括资实际的status,可以用--export排除 kubectl get pod my-pod -l app=nginx # 查看所有带有标签app: nginx的pod

kubectl 可用JSONPATH来过滤字段,JSON Path的语法可参考这里

kubectl get pods --selector=app=cassandra rc -o jsonpath='{.items[*].metadata.labels.version}' # 获取所有具有 app=cassandra 的 pod 中的 version 标签

  • describe describe命令同样用于查看资源信息,但相比与get只输出资源本身的信息,describe聚合了相关资源的信息并输出。比如,在describe node信息时,同时会输出该node下的pod的资源利用情况。所以describe命令在排错和调试时非常有用。

# Usage: kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME) [options] # Examples: kubectl describe nodes my-node # 查看节点my-node的详细信息 kubectl describe pods my-pod # 查看pod my-pod的详细信息

(6)容器管理

虽然逻辑上,Kubernetes的最小管理单位是Pod,但是实际上还是免不了与容器直接交互,特别是对于多容器的Pod,任意容器有问题,都会导致Pod不可用。

  • 日志查看

# Usage: kubectl logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER] [options] # Examples: kubectl logs my-pod # 输出一个单容器pod my-pod的日志到标准输出 kubectl logs nginx-78f5d695bd-czm8z -c nginx # 输出多容器pod中的某个nginx容器的日志 kubectl logs -l app=nginx # 输出所有包含app-nginx标签的pod日志 kubectl logs -f my-pod # 加上-f参数跟踪日志,类似tail -f kubectl logs my-pod -p # 输出该pod的上一个退出的容器实例日志。在pod容器异常退出时很有用 kubectl logs my-pod --since-time=2018-11-01T15:00:00Z # 指定时间戳输出日志 kubectl logs my-pod --since=1h # 指定时间段输出日志,单位s/m/h

  • 执行命令 命令作用和参数基本与docker exec一致

# Usage: kubectl exec POD [-c CONTAINER] -- COMMAND [args...] [options] # Examples: kubectl exec my-pod ls # 对my-pod执行ls命令 kubectl exec -t -i nginx-78f5d695bd-czm8z bash # 进入pod的shell,并打开伪终端和标准输入

  • 文件传输 在排错和测试服务的时候,时不时需要和容器互相交互文件,比如传输容器内存的dump到宿主机,或从宿主机临时拷贝个新配置文件做调试,这时就可以用*kubectl cp命令。要注意的是,cp命令需要容器里已安装有tar程序

# Usage: kubectl cp <file-spec-src> <file-spec-dest> [options] # Examples: kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir # 拷贝宿主机本地文件夹到pod kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar # 指定namespace的拷贝pod文件到宿主机本地目录 kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container> # 对于多容器pod,用-c指定容器名

(7)集群管理

除了和具体的资源打交道,在对集群进行维护时,也经常需要查看集群信息和对节点进行管理,集群管理有以下这些常用的命令:

  • 集群信息查看

kubectl cluster-info # 查看master和集群服务的地址 kubectl cluster-info dump # 查看集群详细日志 kubectl version # 查看Kubernetes集群和客户端版本

  • 节点管理 在集群节点出问题时,可能希望把一个节点不再被调度pod,或把节点目前的pod都驱逐出去

kubectl cordon my-node # 标记 my-node 为 unschedulable,禁止pod被调度过来。注意这时现有的pod还会继续运行,不会被驱逐。 kubectl uncordon my-node # 与cordon相反,标记 my-node 为 允许调度。 kubectl drain my-node # drain字面意思为排水,实际就是把my-node的pod平滑切换到其他node,同时标记pod为unschedulable,也就是包含了cordon命令。 # 但是直接使用命令一般不会成功,建议在要维护节点时,加上以下参数: kubectl drain my-node --ignore-daemonsets --force --delete-local-data # --ignore-daemonsets 忽略daemonset部署的pod # --force 直接删除不由workload对象(Deployment、Job等)管理的pod # --delete-local-data 直接删除挂载有本地目录(empty-dir方式)的pod

(8)kubectl命令汇总

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 debug Create debugging sessions for troubleshooting workloads and nodes 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 replace Replace a resource by filename or stdin wait Experimental: Wait for a specific condition on one or many resources. 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]

参考

(1)英文官方 - https://kubernetes.io/docs/reference/kubectl/overview/

(2)中文文档 - http://docs.kubernetes.org.cn/683.html

(3)Kubectl常用命令详解 https://blog.csdn.net/weixin_44631350/article/details/89450781

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页