龙空技术网

第3课 Kubectl常用命令详解

辉哥的技术投资路 211

前言:

现在大家对“kubectl删除service”大约比较注重,我们都想要知道一些“kubectl删除service”的相关内容。那么小编也在网摘上收集了一些对于“kubectl删除service””的相关资讯,希望姐妹们能喜欢,朋友们一起来了解一下吧!

摘要

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

内容(1)Kubectl常用子命令分类(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.selectorKIND:     DeploymentVERSION:  extensions/v1beta1RESOURCE: 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 podsNAME                     READY   STATUS    RESTARTS   AGEgoweb-6b5d559869-4x5mb   1/1     Running   0          14sgoweb-6b5d559869-77lbz   1/1     Running   0          14sgoweb-6b5d559869-9ztkh   1/1     Running   0          14sgoweb-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 podsNAME                     READY   STATUS    RESTARTS   AGEgoweb-6b5d559869-4x5mb   1/1     Running   0          8m21sgoweb-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 # 创建一个deplpymement

kubectl 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中所有的Podkubectl 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 -fkubectl 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                 # 拷贝宿主机本地文件夹到podkubectl 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 objectsBasic 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 selectorDeploy 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 ReplicationControllerCluster 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 nodesTroubleshooting 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 nodesAdvanced 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 informationUsage:  kubectl [flags] [options]
参考

(1)英文官方 -

(2)中文文档 -

(3)Kubectl常用命令详解

标签: #kubectl删除service #kubectl删除容器 #kubectl删除标签 #kubectl label 删除标签命令