3、Kubernetes集群命令行工具kubectl

目录

一、概述

二、kubectl 命令格式

三、kubectl 帮助命令

四、kubectl 基础命令

4.1、kubectl create创建资源

4.2、kubectl expose暴露pod

4.3、kubectl get获取资源

4.4、kubectl delete删除资源

4.5、kubectl explain查看API对象支持的属性

4.6、kubectl label操作资源标签

五、kubectl 部署命令

5.1、kubectl scale扩容资源

5.2、kubectl rollout管理资源的发布

六、kubectl 集群管理命令

6.1、kubectl cluster-info显示集群信息

6.2、kubectl top显示资源 (CPU/Memory)

6.3、kubectl taint添加污点

七、kubectl 故障和调试命令

7.1、kubectl describe查看资源详细信息

7.2、kubectl exec到 pod 中执行一条命令

7.3、kubectl logs查看Pod日志

7.4、kubectl attach查看实时信息

八、kubectl 其它命令


一、概述

kubectl 是 Kubernetes 集群的命令行工具,通过 kubectl 能够对集群本身进行管理,并能够在集群上进行容器化应用的安装和部署。

二、kubectl 命令格式

kubectl [command] [type] [name] [flags]

参数说明:

  • command:指定要对资源执行的操作,例如 create、get、describe、delete;
  • type:指定资源类型,资源类型是大小写敏感的,开发者能够以单数 、复数和缩略的形式。例如:
$ kubectl get pod nginx
$ kubectl get pods nginx
$ kubectl get po nginx
  • name:指定资源的名称,名称也是大小写敏感的,如果省略名称,则会显示所有的资源,例如:
$ kubectl get pods
  • flags:指定可选的参数,例如,可用 -s 或者 -server 参数指定 Kubernetes API server 的地址和端口;

三、kubectl 帮助命令

获取 kubectl 的命令:

$ kubectl --help
kubectl controls the Kubernetes cluster manager.

 Find more information at: https://kubernetes.io/docs/reference/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         Get documentation for a resource
  get             Display one or many resources
  edit            Edit a resource on the server
  delete          Delete resources by file names, 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, replica set, or replication controller
  autoscale       Auto-scale a deployment, replica set, stateful set, or replication controller

Cluster Management Commands:
  certificate     Modify certificate resources.
  cluster-info    Display cluster information
  top             Display resource (CPU/memory) 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
  events          List events

Advanced Commands:
  diff            Diff the live version against a would-be applied version
  apply           Apply a configuration to a resource by file name or stdin
  patch           Update fields of a resource
  replace         Replace a resource by file name or stdin
  wait            Experimental: Wait for a specific condition on one or many resources
  kustomize       Build a kustomization target from a directory or 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, zsh, fish, or powershell)

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

获取某个命令的介绍和使用:

$ kubectl get --help
Display one or many resources.

 Prints a table of the most important information about the specified resources. You can filter the list using a label
selector and the --selector flag. If the desired resource type is namespaced you will only see results in your current
namespace unless you pass --all-namespaces.

 By specifying the output as 'template' and providing a Go template as the value of the --template flag, you can filter
the attributes of the fetched resources.

Use "kubectl api-resources" for a complete list of supported resources.

Examples:
  # List all pods in ps output format
  kubectl get pods
  
  # List all pods in ps output format with more information (such as node name)
  kubectl get pods -o wide
  
  # List a single replication controller with specified NAME in ps output format
  kubectl get replicationcontroller web
  
  # List deployments in JSON output format, in the "v1" version of the "apps" API group
  kubectl get deployments.v1.apps -o json
  
  # List a single pod in JSON output format
  kubectl get -o json pod web-pod-13je7
  
  # List a pod identified by type and name specified in "pod.yaml" in JSON output format
  kubectl get -f pod.yaml -o json
  
  # List resources from a directory with kustomization.yaml - e.g. dir/kustomization.yaml
  kubectl get -k dir/
  
  # Return only the phase value of the specified pod
  kubectl get -o template pod/web-pod-13je7 --template={
   
   {.status.phase}}
  
  # List resource information in custom columns
  kubectl get pod test-pod -o custom-columns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image
  
  # List all replication controllers and services together in ps output format
  kubectl get rc,services
  
  # List one or more resources by their type and names
  kubectl get rc/web service/frontend pods/web-pod-13je7
  
  # List status subresource for a single pod.
  kubectl get pod web-pod-13je7 --subresource status

Options:
    -A, --all-namespaces=false:
        If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even
        if specified with --namespace.

    --allow-missing-template-keys=true:
        If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to
        golang and jsonpath output formats.

    --chunk-size=500:
        Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and may change in
        the future.

    --field-selector='':
        Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector
        key1=value1,key2=value2). The server only supports a limited number of field queries per type.

    -f, --filename=[]:
        Filename, directory, or URL to files identifying the resource to get from a server.

    --ignore-not-found=false:
        If the requested object does not exist the command will return exit code 0.

    -k, --kustomize='':
        Process the kustomization directory. This flag can't be used together with -f or -R.

    -L, --label-columns=[]:
        Accepts a comma separated list of labels that are going to be presented as columns. Names are case-sensitive.
        You can also use multiple flag options like -L label1 -L label2...

    --no-headers=false:
        When using the default or custom-column output format, don't print headers (default print headers).

    -o, --output='':
        Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath,
        jsonpath-as-json, jsonpath-file, custom-columns, custom-columns-file, wide). See custom columns
        [https://kubernetes.io/docs/reference/kubectl/#custom-columns], golang template
        [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template
        [https://kubernetes.io/docs/reference/kubectl/jsonpath/].

    --output-watch-events=false:
        Output watch event objects when --watch or --watch-only is used. Existing objects are output as initial ADDED
        events.

    --raw='':
        Raw URI to request from the server.  Uses the transport specified by the kubeconfig file.

    -R, --recursive=false:
        Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests
        organized within the same directory.

    -l, --selector='':
        Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching
        objects must satisfy all of the specified label constraints.

    --server-print=true:
        If true, have the server return the appropriate table output. Supports extension APIs and CRDs.

    --show-kind=false:
        If present, list the resource type for the requested object(s).

    --show-labels=false:
        When printing, show all labels as the last column (default hide labels column)

    --show-managed-fields=false:
        If true, keep the managedFields when printing objects in JSON or YAML format.

    --sort-by='':
        If non-empty, sort list types using this field specification.  The field specification is expressed as a
        JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath
        expression must be an integer or a string.

    --subresource='':
        If specified, gets the subresource of the requested object. Must be one of [status scale]. This flag is alpha
        and may change in the future.

    --template='':
        Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format
        is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

    -w, --watch=false:
        After listing/getting the requested object, watch for changes.

    --watch-only=false:
        Watch for changes to the requested object(s), without listing/getting first.

Usage:
  kubectl get
[(-o|--output=)json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file|custom-columns|custom-columns-file|wide]
(TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags] [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

四、kubectl 基础命令

命令

介绍

create

通过文件名或标准输入创建资源

expose

将一个资源公开为一个新的 Service

run

在集群中运行一个特定的镜像

set

在对象上设置特定的功能

get

显示一个或多个资源

explain

文档参考资料

edit

使用默认的编辑器编辑一个资源

delete

通过文件名,标准输入,资源名称或标签来删除资源

scale

扩容

label

更新资源上的标签

4.1、kubectl create创建资源

# 创建一个tomcat6的pod
[root@localhost ~]# kubectl create deployment tomcat6 --image=tomcat:6.0.53-jre8
deployment.apps/tomcat6 created

4.2、kubectl expose暴露pod

## 将一个资源公开为一个新的 Service
[root@localhost ~]# kubectl expose deployment tomcat6 --port=80 --target-port=8080 --type=NodePort 
service/tomcat6 exposed


[root@localhost ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        14m
tomcat6      NodePort    10.110.181.28   <none>        80:30496/TCP   5s

Pod的80映射容器的8080端口,service会代理Pod的80端口。使用【IP:30496】就可以访问tomcat主页。

4.3、kubectl get获取资源

## 获取所有资源
[root@localhost ~]# kubectl get all
NAME                           READY   STATUS              RESTARTS   AGE
pod/tomcat6-56fcc999cb-q8xbv   0/1     ContainerCreating   0          16s

NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   3m20s

NAME                      READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/tomcat6   0/1     1            0           17s

NAME                                 DESIRED   CURRENT   READY   AGE
replicaset.apps/tomcat6-56fcc999cb   1         1         0       17s

## 获取pod
[root@localhost ~]# kubectl get pod
NAME                       READY   STATUS    RESTARTS   AGE
tomcat6-56fcc999cb-q8xbv   1/1     Running   0          2m5s

## 获取pod详细信息
[root@localhost ~]# kubectl get pod -o wide
NAME                       READY   STATUS    RESTARTS   AGE     IP              NODE     NOMINATED NODE   READINESS GATES
tomcat6-56fcc999cb-q8xbv   1/1     Running   0          2m51s   10.244.140.65   node02   <none>           <none>

# 查看所有命名空间的pod
[root@localhost ~]# kubectl get pods --all-namespaces
NAMESPACE     NAME                                       READY   STATUS    RESTARTS   AGE
default       tomcat6-56fcc999cb-q8xbv                   1/1     Running   0          4m11s        5m47s
kube-system   coredns-59d64cd4d4-7vbft                   1/1     Running   0          6m59s
kube-system   coredns-59d64cd4d4-ln8x5                   1/1     Running   0          6m59s
kube-system   etcd-master                                1/1     Running   0          7m5s
kube-system   kube-apiserver-master                      1/1     Running   0          7m5s
kube-system   kube-controller-manager-master             1/1     Running   0          5m3s
kube-system   kube-flannel-ds-amd64-cf86p                1/1     Running   0          6m17s
kube-system   kube-flannel-ds-amd64-dmbt2                1/1     Running   0          6m17s
kube-system   kube-flannel-ds-amd64-ll24v                1/1     Running   0          6m17s
kube-system   kube-proxy-frtzk                           1/1     Running   0          6m59s
kube-system   kube-proxy-k5kzw                           1/1     Running   0          6m29s
kube-system   kube-proxy-wzcws                           1/1     Running   0          6m28s
kube-system   kube-scheduler-master                      1/1     Running   0          5m17s

# 使用-n参数查看指定命名空间的pod
[root@localhost ~]# kubectl get pods -n default
NAME                       READY   STATUS    RESTARTS   AGE
tomcat6-56fcc999cb-q8xbv   1/1     Running   0          4m36s

## 获取service
[root@localhost ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        14m
tomcat6      NodePort    10.110.181.28   <none>        80:30496/TCP   5s

4.4、kubectl delete删除资源

[root@localhost ~]# kubectl get all
NAME                           READY   STATUS    RESTARTS   AGE
pod/tomcat6-56fcc999cb-8wjtv   1/1     Running   0          88s
pod/tomcat6-56fcc999cb-q8xbv   1/1     Running   0          22m
pod/tomcat6-56fcc999cb-rrl8b   1/1     Running   0          88s

NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
service/kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        25m
service/tomcat6      NodePort    10.110.181.28   <none>        80:30496/TCP   10m

NAME                      READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/tomcat6   3/3     3            3           22m

NAME                                 DESIRED   CURRENT   READY   AGE
replicaset.apps/tomcat6-56fcc999cb   3         3         3       22m

## 删除deployment信息
[root@localhost ~]# kubectl delete deployment.apps/tomcat6
deployment.apps "tomcat6" deleted

## 删除完之后只剩下service信息
[root@localhost ~]# kubectl get all
NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
service/kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        27m
service/tomcat6      NodePort    10.110.181.28   <none>        80:30496/TCP   12m

# 删除完之后默认命名空间中没有任何pod
[root@localhost ~]# kubectl get pods
No resources found in default namespace.

# 删除service
[root@localhost ~]# kubectl get all
NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
service/kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        27m
service/tomcat6      NodePort    10.110.181.28   <none>        80:30496/TCP   12m
[root@localhost ~]# kubectl delete service/tomcat6 
service "tomcat6" deleted
[root@localhost ~]# kubectl get all
NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   28m

4.5、kubectl explain查看API对象支持的属性

explain获取资源及其字段的文档,例如:kubectl explain pods、kubectl explain pods.spec.containers等。

$ kubectl explain pods
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
$ kubectl explain pod.metadata
KIND:     Pod
VERSION:  v1

RESOURCE: metadata <Object>

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

     ObjectMeta is metadata that all persisted resources must have, which
     includes all objects users must create.

FIELDS:
   annotations  <map[string]string>
     Annotations is an unstructured key value map stored with a resource that
     may be set by external tools to store and retrieve arbitrary metadata. They
     are not queryable and should be preserved when modifying objects. More
     info: http://kubernetes.io/docs/user-guide/annotations

   creationTimestamp    <string>
     CreationTimestamp is a timestamp representing the server time when this
     object was created. It is not guaranteed to be set in happens-before order
     across separate operations. Clients may not set this value. It is
     represented in RFC3339 form and is in UTC.

     Populated by the system. Read-only. Null for lists. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   deletionGracePeriodSeconds   <integer>
     Number of seconds allowed for this object to gracefully terminate before it
     will be removed from the system. Only set when deletionTimestamp is also
     set. May only be shortened. Read-only.

   deletionTimestamp    <string>
     DeletionTimestamp is RFC 3339 date and time at which this resource will be
     deleted. This field is set by the server when a graceful deletion is
     requested by the user, and is not directly settable by a client. The
     resource is expected to be deleted (no longer visible from resource lists,
     and not reachable by name) after the time in this field, once the
     finalizers list is empty. As long as the finalizers list contains items,
     deletion is blocked. Once the deletionTimestamp is set, this value may not
     be unset or be set further into the future, although it may be shortened or
     the resource may be deleted prior to this time. For example, a user may
     request that a pod is deleted in 30 seconds. The Kubelet will react by
     sending a graceful termination signal to the containers in the pod. After
     that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL)
     to the container and after cleanup, remove the pod from the API. In the
     presence of network partitions, this object may still exist after this
     timestamp, until an administrator or automated process can determine the
     resource is fully terminated. If not set, graceful deletion of the object
     has not been requested.

     Populated by the system when a graceful deletion is requested. Read-only.
     More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   finalizers   <[]string>
     Must be empty before the object is deleted from the registry. Each entry is
     an identifier for the responsible component that will remove the entry from
     the list. If the deletionTimestamp of the object is non-nil, entries in
     this list can only be removed. Finalizers may be processed and removed in
     any order. Order is NOT enforced because it introduces significant risk of
     stuck finalizers. finalizers is a shared field, any actor with permission
     can reorder it. If the finalizer list is processed in order, then this can
     lead to a situation in which the component responsible for the first
     finalizer in the list is waiting for a signal (field value, external
     system, or other) produced by a component responsible for a finalizer later
     in the list, resulting in a deadlock. Without enforced ordering finalizers
     are free to order amongst themselves and are not vulnerable to ordering
     changes in the list.

   generateName <string>
     GenerateName is an optional prefix, used by the server, to generate a
     unique name ONLY IF the Name field has not been provided. If this field is
     used, the name returned to the client will be different than the name
     passed. This value will also be combined with a unique suffix. The provided
     value has the same validation rules as the Name field, and may be truncated
     by the length of the suffix required to make the value unique on the
     server.

     If this field is specified and the generated name exists, the server will
     return a 409.

     Applied only if Name is not specified. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency

   generation   <integer>
     A sequence number representing a specific generation of the desired state.
     Populated by the system. Read-only.

   labels       <map[string]string>
     Map of string keys and values that can be used to organize and categorize
     (scope and select) objects. May match selectors of replication controllers
     and services. More info: http://kubernetes.io/docs/user-guide/labels

   managedFields        <[]Object>
     ManagedFields maps workflow-id and version to the set of fields that are
     managed by that workflow. This is mostly for internal housekeeping, and
     users typically shouldn't need to set or understand this field. A workflow
     can be the user's name, a controller's name, or the name of a specific
     apply path like "ci-cd". The set of fields is always in the version that
     the workflow used when modifying the object.

   name <string>
     Name must be unique within a namespace. Is required when creating
     resources, although some resources may allow a client to request the
     generation of an appropriate name automatically. Name is primarily intended
     for creation idempotence and configuration definition. Cannot be updated.
     More info: http://kubernetes.io/docs/user-guide/identifiers#names

   namespace    <string>
     Namespace defines the space within which each name must be unique. An empty
     namespace is equivalent to the "default" namespace, but "default" is the
     canonical representation. Not all objects are required to be scoped to a
     namespace - the value of this field for those objects will be empty.

     Must be a DNS_LABEL. Cannot be updated. More info:
     http://kubernetes.io/docs/user-guide/namespaces

   ownerReferences      <[]Object>
     List of objects depended by this object. If ALL objects in the list have
     been deleted, this object will be garbage collected. If this object is
     managed by a controller, then an entry in this list will point to this
     controller, with the controller field set to true. There cannot be more
     than one managing controller.

   resourceVersion      <string>
     An opaque value that represents the internal version of this object that
     can be used by clients to determine when objects have changed. May be used
     for optimistic concurrency, change detection, and the watch operation on a
     resource or set of resources. Clients must treat these values as opaque and
     passed unmodified back to the server. They may only be valid for a
     particular resource or set of resources.

     Populated by the system. Read-only. Value must be treated as opaque by
     clients and . More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency

   selfLink     <string>
     Deprecated: selfLink is a legacy read-only field that is no longer
     populated by the system.

   uid  <string>
     UID is the unique in time and space value for this object. It is typically
     generated by the server on successful creation of a resource and is not
     allowed to change on PUT operations.

     Populated by the system. Read-only. More info:
     http://kubernetes.io/docs/user-guide/identifiers#uids
$ kubectl explain pod.spec    
KIND:     Pod
VERSION:  v1

RESOURCE: spec <Object>

DESCRIPTION:
     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

     PodSpec is a description of a pod.

FIELDS:
   activeDeadlineSeconds        <integer>
     Optional duration in seconds the pod may be active on the node relative to
     StartTime before the system will actively try to mark it failed and kill
     associated containers. Value must be a positive integer.

   affinity     <Object>
     If specified, the pod's scheduling constraints

   automountServiceAccountToken <boolean>
     AutomountServiceAccountToken indicates whether a service account token
     should be automatically mounted.

   containers   <[]Object> -required-
     List of containers belonging to the pod. Containers cannot currently be
     added or removed. There must be at least one container in a Pod. Cannot be
     updated.

   dnsConfig    <Object>
     Specifies the DNS parameters of a pod. Parameters specified here will be
     merged to the generated DNS configuration based on DNSPolicy.

   dnsPolicy    <string>
     Set DNS policy for the pod. Defaults to "ClusterFirst". Valid values are
     'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS
     parameters given in DNSConfig will be merged with the policy selected with
     DNSPolicy. To have DNS options set along with hostNetwork, you have to
     specify DNS policy explicitly to 'ClusterFirstWithHostNet'.

     Possible enum values:
     - `"ClusterFirst"` indicates that the pod should use cluster DNS first
     unless hostNetwork is true, if it is available, then fall back on the
     default (as determined by kubelet) DNS settings.
     - `"ClusterFirstWithHostNet"` indicates that the pod should use cluster DNS
     first, if it is available, then fall back on the default (as determined by
     kubelet) DNS settings.
     - `"Default"` indicates that the pod should use the default (as determined
     by kubelet) DNS settings.
     - `"None"` indicates that the pod should use empty DNS settings. DNS
     parameters such as nameservers and search paths should be defined via
     DNSConfig.

   enableServiceLinks   <boolean>
     EnableServiceLinks indicates whether information about services should be
     injected into pod's environment variables, matching the syntax of Docker
     links. Optional: Defaults to true.

   ephemeralContainers  <[]Object>
     List of ephemeral containers run in this pod. Ephemeral containers may be
     run in an existing pod to perform user-initiated actions such as debugging.
     This list cannot be specified when creating a pod, and it cannot be
     modified by updating the pod spec. In order to add an ephemeral container
     to an existing pod, use the pod's ephemeralcontainers subresource.

   hostAliases  <[]Object>
     HostAliases is an optional list of hosts and IPs that will be injected into
     the pod's hosts file if specified. This is only valid for non-hostNetwork
     pods.

   hostIPC      <boolean>
     Use the host's ipc namespace. Optional: Default to false.

   hostNetwork  <boolean>
     Host networking requested for this pod. Use the host's network namespace.
     If this option is set, the ports that will be used must be specified.
     Default to false.

   hostPID      <boolean>
     Use the host's pid namespace. Optional: Default to false.

   hostUsers    <boolean>
     Use the host's user namespace. Optional: Default to true. If set to true or
     not present, the pod will be run in the host user namespace, useful for
     when the pod needs a feature only available to the host user namespace,
     such as loading a kernel module with CAP_SYS_MODULE. When set to false, a
     new userns is created for the pod. Setting false is useful for mitigating
     container breakout vulnerabilities even allowing users to run their
     containers as root without actually having root privileges on the host.
     This field is alpha-level and is only honored by servers that enable the
     UserNamespacesSupport feature.

   hostname     <string>
     Specifies the hostname of the Pod If not specified, the pod's hostname will
     be set to a system-defined value.

   imagePullSecrets     <[]Object>
     ImagePullSecrets is an optional list of references to secrets in the same
     namespace to use for pulling any of the images used by this PodSpec. If
     specified, these secrets will be passed to individual puller
     implementations for them to use. More info:
     https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod

   initContainers       <[]Object>
     List of initialization containers belonging to the pod. Init containers are
     executed in order prior to containers being started. If any init container
     fails, the pod is considered to have failed and is handled according to its
     restartPolicy. The name for an init container or normal container must be
     unique among all containers. Init containers may not have Lifecycle
     actions, Readiness probes, Liveness probes, or Startup probes. The
     resourceRequirements of an init container are taken into account during
     scheduling by finding the highest request/limit for each resource type, and
     then using the max of of that value or the sum of the normal containers.
     Limits are applied to init containers in a similar fashion. Init containers
     cannot currently be added or removed. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/init-containers/

   nodeName     <string>
     NodeName is a request to schedule this pod onto a specific node. If it is
     non-empty, the scheduler simply schedules this pod onto that node, assuming
     that it fits resource requirements.

   nodeSelector <map[string]string>
     NodeSelector is a selector which must be true for the pod to fit on a node.
     Selector which must match a node's labels for the pod to be scheduled on
     that node. More info:
     https://kubernetes.io/docs/concepts/configuration/assign-pod-node/

   os   <Object>
     Specifies the OS of the containers in the pod. Some pod and container
     fields are restricted if this is set.

     If the OS field is set to linux, the following fields must be unset:
     -securityContext.windowsOptions

     If the OS field is set to windows, following fields must be unset: -
     spec.hostPID - spec.hostIPC - spec.hostUsers -
     spec.securityContext.seLinuxOptions - spec.securityContext.seccompProfile -
     spec.securityContext.fsGroup - spec.securityContext.fsGroupChangePolicy -
     spec.securityContext.sysctls - spec.shareProcessNamespace -
     spec.securityContext.runAsUser - spec.securityContext.runAsGroup -
     spec.securityContext.supplementalGroups -
     spec.containers[*].securityContext.seLinuxOptions -
     spec.containers[*].securityContext.seccompProfile -
     spec.containers[*].securityContext.capabilities -
     spec.containers[*].securityContext.readOnlyRootFilesystem -
     spec.containers[*].securityContext.privileged -
     spec.containers[*].securityContext.allowPrivilegeEscalation -
     spec.containers[*].securityContext.procMount -
     spec.containers[*].securityContext.runAsUser -
     spec.containers[*].securityContext.runAsGroup

   overhead     <map[string]string>
     Overhead represents the resource overhead associated with running a pod for
     a given RuntimeClass. This field will be autopopulated at admission time by
     the RuntimeClass admission controller. If the RuntimeClass admission
     controller is enabled, overhead must not be set in Pod create requests. The
     RuntimeClass admission controller will reject Pod create requests which
     have the overhead already set. If RuntimeClass is configured and selected
     in the PodSpec, Overhead will be set to the value defined in the
     corresponding RuntimeClass, otherwise it will remain unset and treated as
     zero. More info:
     https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead/README.md

   preemptionPolicy     <string>
     PreemptionPolicy is the Policy for preempting pods with lower priority. One
     of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.

   priority     <integer>
     The priority value. Various system components use this field to find the
     priority of the pod. When Priority Admission Controller is enabled, it
     prevents users from setting this field. The admission controller populates
     this field from PriorityClassName. The higher the value, the higher the
     priority.

   priorityClassName    <string>
     If specified, indicates the pod's priority. "system-node-critical" and
     "system-cluster-critical" are two special keywords which indicate the
     highest priorities with the former being the highest priority. Any other
     name must be defined by creating a PriorityClass object with that name. If
     not specified, the pod priority will be default or zero if there is no
     default.

   readinessGates       <[]Object>
     If specified, all readiness gates will be evaluated for pod readiness. A
     pod is ready when all its containers are ready AND all conditions specified
     in the readiness gates have status equal to "True" More info:
     https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates

   resourceClaims       <[]Object>
     ResourceClaims defines which ResourceClaims must be allocated and reserved
     before the Pod is allowed to start. The resources will be made available to
     those containers which consume them by name.

     This is an alpha field and requires enabling the DynamicResourceAllocation
     feature gate.

     This field is immutable.

   restartPolicy        <string>
     Restart policy for all containers within the pod. One of Always, OnFailure,
     Never. Default to Always. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy

     Possible enum values:
     - `"Always"`
     - `"Never"`
     - `"OnFailure"`

   runtimeClassName     <string>
     RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group,
     which should be used to run this pod. If no RuntimeClass resource matches
     the named class, the pod will not be run. If unset or empty, the "legacy"
     RuntimeClass will be used, which is an implicit class with an empty
     definition that uses the default runtime handler. More info:
     https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class

   schedulerName        <string>
     If specified, the pod will be dispatched by specified scheduler. If not
     specified, the pod will be dispatched by default scheduler.

   schedulingGates      <[]Object>
     SchedulingGates is an opaque list of values that if specified will block
     scheduling the pod. More info:
     https://git.k8s.io/enhancements/keps/sig-scheduling/3521-pod-scheduling-readiness.

     This is an alpha-level feature enabled by PodSchedulingReadiness feature
     gate.

   securityContext      <Object>
     SecurityContext holds pod-level security attributes and common container
     settings. Optional: Defaults to empty. See type description for default
     values of each field.

   serviceAccount       <string>
     DeprecatedServiceAccount is a depreciated alias for ServiceAccountName.
     Deprecated: Use serviceAccountName instead.

   serviceAccountName   <string>
     ServiceAccountName is the name of the ServiceAccount to use to run this
     pod. More info:
     https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/

   setHostnameAsFQDN    <boolean>
     If true the pod's hostname will be configured as the pod's FQDN, rather
     than the leaf name (the default). In Linux containers, this means setting
     the FQDN in the hostname field of the kernel (the nodename field of struct
     utsname). In Windows containers, this means setting the registry value of
     hostname for the registry key
     HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters to
     FQDN. If a pod does not have FQDN, this has no effect. Default to false.

   shareProcessNamespace        <boolean>
     Share a single process namespace between all of the containers in a pod.
     When this is set containers will be able to view and signal processes from
     other containers in the same pod, and the first process in each container
     will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both
     be set. Optional: Default to false.

   subdomain    <string>
     If specified, the fully qualified Pod hostname will be
     "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>". If not
     specified, the pod will not have a domainname at all.

   terminationGracePeriodSeconds        <integer>
     Optional duration in seconds the pod needs to terminate gracefully. May be
     decreased in delete request. Value must be non-negative integer. The value
     zero indicates stop immediately via the kill signal (no opportunity to shut
     down). If this value is nil, the default grace period will be used instead.
     The grace period is the duration in seconds after the processes running in
     the pod are sent a termination signal and the time when the processes are
     forcibly halted with a kill signal. Set this value longer than the expected
     cleanup time for your process. Defaults to 30 seconds.

   tolerations  <[]Object>
     If specified, the pod's tolerations.

   topologySpreadConstraints    <[]Object>
     TopologySpreadConstraints describes how a group of pods ought to spread
     across topology domains. Scheduler will schedule pods in a way which abides
     by the constraints. All topologySpreadConstraints are ANDed.

   volumes      <[]Object>
     List of volumes that can be mounted by containers belonging to the pod.
     More info: https://kubernetes.io/docs/concepts/storage/volumes

4.6、kubectl label操作资源标签

# 给pod添加标签
$ kubectl label pod nginx-748c667d99-v22h8 environment=dev
pod/nginx-748c667d99-v22h8 labeled

# 查看pod标签
$ kubectl get pod --show-labels
NAME                     READY   STATUS    RESTARTS   AGE     LABELS
nginx-748c667d99-v22h8   1/1     Running   0          6m37s   app=nginx,environment=dev,pod-template-hash=748c667d99

五、kubectl 部署命令

命令

介绍

rollout

管理资源的发布

rolling-update

对给定的复制控制器滚动更新

scale

扩容或缩容 Pod 数量,Deployment、ReplicaSet、RC 或 Job

autoscale

创建一个自动选择扩容或缩容并设置 Pod 数量

5.1、kubectl scale扩容资源

[root@localhost ~]# kubectl create deployment tomcat6 --image=tomcat:6.0.53-jre8
deployment.apps/tomcat6 created

## 使用--replicas=3指定扩容数量
[root@localhost ~]# kubectl scale --replicas=3 deployment tomcat6
deployment.apps/tomcat6 scaled

[root@localhost ~]# kubectl get pods -o wide
NAME                       READY   STATUS    RESTARTS   AGE   IP              NODE     NOMINATED NODE   READINESS GATES
tomcat6-56fcc999cb-8wjtv   1/1     Running   0          10s   10.244.140.66   node02   <none>           <none>
tomcat6-56fcc999cb-q8xbv   1/1     Running   0          20m   10.244.140.65   node02   <none>           <none>
tomcat6-56fcc999cb-rrl8b   1/1     Running   0          10s   10.244.140.67   node02   <none>           <none>

5.2、kubectl rollout管理资源的发布

$ kubectl create deployment nginx --image=nginx:1.14
deployment.apps/nginx created

$ kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-7ccbcfc8d5-vz4v8   1/1     Running   0          10s

$ kubectl set image deployment nginx nginx=nginx:1.15
deployment.apps/nginx image updated

# 查看升级状态
$ kubectl rollout status deployment nginx
deployment "nginx" successfully rolled out

# 查看历史版本
$ kubectl rollout history deployment nginx
deployment.apps/nginx 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>

# 回滚到上一版本
$ kubectl rollout undo deployment nginx

# 回滚到指定版本
$ kubectl rollout undo deployment nginx --to-revision=2

六、kubectl 集群管理命令

命令

介绍

certificate

修改证书资源

cluster-info

显示集群信息

top

显示资源 (CPU/Memory)

cordon

标记节点不可调度

uncordon

标记节点可被调度

drain

驱逐节点上的应用,准备下线维护

taint

修改节点 taint (污点)标记

6.1、kubectl cluster-info显示集群信息

$ kubectl cluster-info
Kubernetes control plane is running at https://172.30.1.2:6443
CoreDNS is running at https://172.30.1.2:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

6.2、kubectl top显示资源 (CPU/Memory)

kubectl top命令可显⽰节点和Pod对象的资源使⽤信息,它依赖于集群中的资源指标API来收集各项指标数据。它包含有node和pod两个⼦命令,可分别⽤于显⽰Node对象和Pod对象的相关资源占⽤率。

$ kubectl top
Display Resource (CPU/Memory) usage.

 The top command allows you to see the resource consumption for nodes or pods.

 This command requires Metrics Server to be correctly configured and working on the server.

Available Commands:
  node          Display resource (CPU/memory) usage of nodes
  pod           Display resource (CPU/memory) usage of pods

Usage:
  kubectl top [flags] [options]

# 查看node的使用情况
$ kubectl top node node01
NAME               CPU(cores)   CPU%   MEMORY(bytes)   MEMORY%   
node01   						2170m        55%    6803Mi          43%       

# 查看 pod 的使用情况
$ kubectl top pod nginx
NAME                                         CPU(cores)   MEMORY(bytes)
nginx														                2m           30Mi

6.3、kubectl taint添加污点

语法:kubectl taint node <node_name> key=value[effect]

$ kubectl get nodes
NAME           STATUS   ROLES           AGE     VERSION
controlplane   Ready    control-plane   4d11h   v1.26.0
node01         Ready    <none>          4d11h   v1.26.0

# 给节点添加污点
$ kubectl taint node node01 key1=value1:NoSchedule
node/node01 tainted

# 查看节点污点
$ kubectl describe node node01 | grep Taints
Taints:             key1=value1:NoSchedule

# 删除节点污点
$ kubectl taint node node01 key1=value1:NoSchedule- 
node/node01 untainted

$ kubectl describe node node01 | grep Taints
Taints:             <none>

七、kubectl 故障和调试命令

命令

介绍

describe

显示特定资源或资源组的详细信息

logs

在一个 Pod 中打印一个容器日志,如果 Pod 只有一个容器,容器名称是可选的

attach

到一个运行中的容器上,实时查看容器消息

exec

用于到 pod 中执行一条命令

port-forward

转发一个或多个

proxy

运行一个 proxy 到 Kubernetes API Server

cp

拷贝文件或目录到容器中

auth

检查授权

7.1、kubectl describe查看资源详细信息

  • kubectl describe pod [Pod-ID]:查看 Pod 的详细描述信息;
  • kubectl describe node [Node-ID]:查看 Node 的详细描述信息;
  • kubectl describe deployment [Deployment-ID]:查看 Deployment 的详细描述信息;
$ kubectl describe pod nginx-748c667d99-v22h8
Name:             nginx-748c667d99-v22h8
Namespace:        default
Priority:         0
Service Account:  default
Node:             node01/172.30.2.2
Start Time:       Tue, 31 Jan 2023 02:15:15 +0000
Labels:           app=nginx
                  pod-template-hash=748c667d99
Annotations:      cni.projectcalico.org/containerID: bc0aa440c8f3927b78e21b5f4026b9446d7f61a695fb5865ff5371c7d6fb2353
                  cni.projectcalico.org/podIP: 192.168.1.3/32
                  cni.projectcalico.org/podIPs: 192.168.1.3/32
Status:           Running
IP:               192.168.1.3
IPs:
  IP:           192.168.1.3
Controlled By:  ReplicaSet/nginx-748c667d99
Containers:
  nginx:
    Container ID:   containerd://abcf3a21b478c65ded9c2e7318c537c4369032e0ea1f3f90eb95ece85a8e4d36
    Image:          nginx
    Image ID:       docker.io/library/nginx@sha256:b8f2383a95879e1ae064940d9a200f67a6c79e710ed82ac42263397367e7cc4e
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Tue, 31 Jan 2023 02:15:21 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-fm8g4 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-fm8g4:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age    From               Message
  ----    ------     ----   ----               -------
  Normal  Scheduled  2m47s  default-scheduler  Successfully assigned default/nginx-748c667d99-v22h8 to node01
  Normal  Pulling    2m47s  kubelet            Pulling image "nginx"
  Normal  Pulled     2m41s  kubelet            Successfully pulled image "nginx" in 5.475376114s (5.475380149s including waiting)
  Normal  Created    2m41s  kubelet            Created container nginx
  Normal  Started    2m41s  kubelet            Started container nginx

7.2、kubectl exec到 pod 中执行一条命令

$ kubectl create deployment nginx --image=nginx
deployment.apps/nginx created

$ kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-748c667d99-v22h8   1/1     Running   0          7s

# 进入容器内部
$ kubectl exec -it nginx-748c667d99-v22h8 -- bin/bash
root@nginx-748c667d99-v22h8:/# pwd
/

7.3、kubectl logs查看Pod日志

$ kubectl logs nginx-748c667d99-v22h8            
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2023/01/31 02:15:21 [notice] 1#1: using the "epoll" event method
2023/01/31 02:15:21 [notice] 1#1: nginx/1.23.3
2023/01/31 02:15:21 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2023/01/31 02:15:21 [notice] 1#1: OS: Linux 5.4.0-131-generic
2023/01/31 02:15:21 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2023/01/31 02:15:21 [notice] 1#1: start worker processes
2023/01/31 02:15:21 [notice] 1#1: start worker process 28

7.4、kubectl attach查看实时信息

kubectl attach 用于取得 Pod 中容器的实时信息,可以持续不断实时的取出消息。

创建一个Pod:

apiVersion: v1
kind: Pod
metadata:
  name: centos
spec:
  terminationGracePeriodSeconds: 60
  containers:
    - name: centos
      image: centos
      command: ["/bin/sh"]
      args: ["-c", "while true; do echo hello; sleep 10;done"]
$ kubectl get pod | grep centos
centos   1/1     Running   0          13s

# 持续不断实时输出容器消息
$ kubectl attach centos
hello
hello
hello
hello
hello
hello
.....

八、kubectl 其它命令

命令

介绍

apply

通过文件名或标准输入对资源应用配置

patch

使用补丁修改、更新资源的字段

replace

通过文件名或标准输入替换一个资源

convert

不同的 API 版本之间转换配置文件

annotate

更新资源上的注释

completion

用f于实现 kubectl 工具自动补全

api-versions

打印受支持的 API 版本

config

修改 kubeconfig 文件(用于访问 API,比如配置认证信息)

plugin

运行一个命令行插件

version

打印客户端和服务版本信息

猜你喜欢

转载自blog.csdn.net/Weixiaohuai/article/details/131897321