kubectl 常用命令总结

317 阅读8分钟

这是我参与更文挑战的第3天,活动详情查看: 更文挑战

一、kubectl 常用命令总结

简单介绍一下 kubectl 的常用命令,一方面方便查阅,另一方面巩固记忆一下这些命令。

在使用命令的时候忘记使用的命令参数,可以通过命令 kubectl 命令 -h 获取更多帮助信息。

1、学习 k8s 最有帮助的命令 kubectl explain

kubectl explain 这个命令对于学习 k8s 是最有帮助的命令,我自己在学习的过程中也经常使用这个命令来查阅相关配置的使用说明,这也是首先介绍这个命令的原因。

kubectl explain 的作用就是用来描述每一个资源相关的字段使用说明,我们可以通过 JSONPath 表示的方式指定要查看的字段: <type>.<fieldName>[.<fieldName>]

使用命令 kubectl explain pod 查看 pod 资源的使用文档和它可以配置的字段:

# 查看 pod 的使用
kubectl explain pod
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion   <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata     <Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec <Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

   status       <Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

上面的命令查看的是 pod 可以使用的一级字段,要查看指定的字段只需要添加相关的子字段即可,比如想要查看 pod 端口的使用说明,可以指定 pod.spec.containers.ports , 命令如下:

# 查看 pod 中容器的端口使用说明
kubectl explain  pod.spec.containers.ports
KIND:     Pod
VERSION:  v1

RESOURCE: ports <[]Object>

DESCRIPTION:
     List of ports to expose from the container. Exposing a port here gives the
     system additional information about the network connections a container
     uses, but is primarily informational. Not specifying a port here DOES NOT
     prevent that port from being exposed. Any port which is listening on the
     default "0.0.0.0" address inside a container will be accessible from the
     network. Cannot be updated.

     ContainerPort represents a network port in a single container.

FIELDS:
   containerPort        <integer> -required-
     Number of port to expose on the pod's IP address. This must be a valid port
     number, 0 < x < 65536.

   hostIP       <string>
     What host IP to bind the external port to.

   hostPort     <integer>
     Number of port to expose on the host. If specified, this must be a valid
     port number, 0 < x < 65536. If HostNetwork is specified, this must match
     ContainerPort. Most containers do not need this.

   name <string>
     If specified, this must be an IANA_SVC_NAME and unique within the pod. Each
     named port in a pod must have a unique name. Name for the port that can be
     referred to by services.

   protocol     <string>
     Protocol for port. Must be UDP, TCP, or SCTP. Defaults to "TCP".

2、k8s 中常用资源对象简写对照表

名称简写所属 api 组是否是命名空间级别类型
componentstatusescsfalseComponentStatus
configmapscmtrueConfigMap
endpointseptrueEndpoints
eventsevtrueEvent
limitrangeslimitstrueLimitRange
namespacesnsfalseNamespace
nodesnofalseNode
persistentvolumeclaimspvctruePersistentVolumeClaim
persistentvolumespvfalsePersistentVolume
podspotruePod
replicationcontrollersrctrueReplicationController
resourcequotasquotatrueResourceQuota
serviceaccountssatrueServiceAccount
servicessvctrueService
customresourcedefinitionscrd,crdsapiextensions.k8s.iofalseCustomResourceDefinition
daemonsetsdsappstrueDaemonSet
deploymentsdeployappstrueDeployment
replicasetsrsappstrueReplicaSet
statefulsetsstsappstrueStatefulSet
horizontalpodautoscalershpaautoscalingtrueHorizontalPodAutoscaler
cronjobscjbatchtrueCronJob
eventsevevents.k8s.iotrueEvent
ingressesingextensionstrueIngress
storageclassesscstorage.k8s.iofalseStorageClass

3、集群管理命令

# 查看集群信息
kubectl cluster-info

# 查看节点资源(cpu/内存)使用情况
kubectl top node

# 查看默认命名空间 pod 资源(cpu/内存)使用情况,并按照 cpu 倒序排序
kubectl top pod --sort-by cpu -n default

# 查看默认命名空间 pod 资源(cpu/内存)使用情况,并按照内存倒序排序
kubectl top pod --sort-by memory -n default

# 不可调度
kubectl cordon node-0

# 当某个节点需要维护时,可以驱逐该节点上的所有pods(会删除节点上的pod,并且自动通过上面命令设置
# 该节点不可调度,然后在其他可用节点重新启动pods)
kubectl drain node-0
# 待其维护完成后,可再设置该节点为可调度
kubectl uncordon node-0

4、创建资源命令

在 k8s 中创建资源通常会将要创建的资源定义在一个 yaml 格式的清单文件中,这个文件可以当做部署文件,使用清单文件的好处是方便复用,这里以创建一个 nginx 为例,创建一个 nginx-deployment.yaml 的资源清单如下:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80

一般创建资源会有两种方式:通过文件或者命令创建,通常使用清单文件创建。


# 使用 create 命令通过文件创建资源
kubectl create -f nginx-depoyment.yaml
deployment.apps/nginx created

# 查看 default 命令空间的 pod
kubectl get pod -n default
NAME                    READY   STATUS    RESTARTS   AGE
nginx-585449566-qkh25   1/1     Running   0          13s

# 再一次使用 create 命令创建,发现报错说创建的资源已经存在
kubectl create -f nginx-depoyment.yaml
Error from server (AlreadyExists): error when creating "nginx-depoyment.yaml": deployments.apps "nginx" already exists

# 使用 apply 命令通过文件创建资源
kubectl apply -f nginx-depoyment.yaml
Warning: kubectl apply should be used on resource created by either kubectl create --save-config or kubectl apply
deployment.apps/nginx configured

# 再次使用 apply 命令创建资源,没有报错,而是检查配置文件是否更新,如果有更新则更新部署
E:\k8s-devops>kubectl apply -f nginx-depoyment.yaml
deployment.apps/nginx unchanged

# 使用 create 命令创建资源
kubectl create deployment my-nginx --image=nginx --replicas=1

说明:创建资源的时候推荐使用 apply 命令,因为资源已存在时,使用 create 命令会报错,而使用 apply 命令不会报错,配置文件发生改变则更新。

kubectl还提供了一些更新资源的命令,比如kubectl editkubectl patchkubectl replace

# kubectl edit 会打开一个编辑器可以让我们直接修改指定资源的清单文件,在linux系统中编辑和vim一样
kubectl edit deploy nginx

# kubectl patch:使用补丁修改、更新某个资源的字段,比如更新 deploy 的pod 副本数
kubectl patch deploy nginx -p '{"spec":{"replicas":3}}'

# kubectl replace:使用配置文件来替换资源
kubectl replace -f /path/to/new_nginx_app.yaml

5、查看资源命令

# 一般命令的格式会如下:
kubectl get <resource_type>
# 比如获取K8s集群下pod的信息
kubectl get pod
# 更加详细的信息
kubectl get pod -o wide
# 指定资源的信息,格式:kubectl get <resource_type> <resource_name>,比如获取deployment nginx的信息
kubectl get deploy nginx -o wide
# 也可以对指定的资源进行格式化输出,比如输出格式为json、yaml等
kubectl get deploy nginx -o yaml
# 还可以对输出结果进行自定义,比如对pod只输出容器名称和镜像名称
kubectl get pod nginx-585449566-4jc2d -o custom-columns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image
# 获取某个特定key的值还可以输入如下命令得到,此目录参照go template的用法,且命令结尾'\n'是为了输出结果换行
kubectl get pod nginx-585449566-4jc2d -o template --template='{{(index spec.containers 0).name}}{{"\n"}}'

6、部署命令


# 资源的暂停及恢复:发出一次或多次更新前暂停一个 Deployment,然后再恢复它,
#这样就能在Deployment暂停期间进行多次修复工作,而不会发出不必要的 rollout。
# 暂停
kubectl rollout pause deployment/nginx
# 完成所有的更新操作命令后进行恢复
kubectl rollout resume deployment/nginx

# 回滚:如上对一个Deployment的image做了更新,但是如果遇到更新失败或误更新等情况时可以对其进行回滚。
# 回滚之前先查看历史版本信息
kubectl rollout history deployment/nginx
# 回滚
kubectl rollout undo deployment/nginx
# 当然也可以指定版本号回滚至指定版本
kubectl rollout undo deployment/nginx --to-revision=<version_index>

# 扩容
kubectl scale deploy nginx --replicas=5
# 如果是缩容,把对应的副本数设置的比当前的副本数小即可
# 另外,还可以针对当前的副本数目做条件限制,比如当前副本数是5则进行缩容至副本数目为3
kubectl scale --current-replicas=5 --replicas=3 deploy nginx

# 基于CPU的使用率创建3-10个pod
kubectl autoscale deployment/nginx --min=3 --max=10 --cpu_percent=80

7、其他经常使用的命令

# 映射端口允许外部访问
kubectl expose deployment/nginx --type='NodePort' --port=80
# 然后通过kubectl get services -o wide来查看被随机映射的端口
# 如此就可以通过node的外部IP和端口来访问nginx服务了

# 转发本地端口访问Pod的应用服务程序
kubectl port-forward deploy nginx 8090:80
# 如此,本地可以访问:curl -i localhost:8090

# 在创建或启动某些资源的时候没有达到预期结果,可以使用如下命令先简单进行故障定位
kubectl describe deployment nginx
# 查看 pod 中容器的日志
kubectl logs -f nginx-585449566-stccl
# 进入 pod 中的容器
kubectl exec -it  nginx-585449566-stccl bash

# 集群内部调用接口(比如用curl命令),可以采用代理的方式,根据返回的ip及端口作为baseurl
kubectl proxy &

# 查看K8s支持的完整资源列表
kubectl api-resources

# 查看K8s支持的api版本
kubectl api-versions