kubectl命令行工具(包括命令扩展方法,1.14之后稳定版支持)


来自官网: https://kubernetes.io/docs/reference/kubectl/


参考有:
https://kubernetes.io/docs/reference/kubectl/kubectl/
https://kubernetes.io/docs/concepts/architecture/nodes/
https://kubernetes.io/docs/concepts/architecture/
https://kubernetes.io/docs/concepts/
https://kubernetes.io/docs/concepts/overview/components/

 kubectl命令工具

Kubernetes provides a command line tool for communicating with a Kubernetes cluster's control plane, using the Kubernetes API.

Kubernetes提供了一个命令行工具,用于使用Kubernetes API与Kubernetes群集的控制平面(可以认为是管理端)进行通信。
工具名称为kubectl,查找工具(这个可以到官方下载对应版本的二进制程序或自己编译都可以)
[root@aozhejin ~]# whereis kubectl
kubectl: /usr/local/bin/kubectl


For configuration, kubectl looks for a file named config in the $HOME/.kube directory. You can specify other kubeconfig files by setting the KUBECONFIG environment variable or by setting the --kubeconfig flag. (这个我们没有意义)

This overview covers kubectl syntax, describes the command operations, and provides common examples. For details about each command, including all the supported flags and subcommands, see the kubectl reference documentation.

本概述介绍kubectl语法,描述命令操作,并提供常见示例。有关每个命令(包括所有受支持的标志和子命令)的详细信息,请参阅kubectl参考文档。

For installation instructions, see Installing kubectl; for a quick guide, see the cheat sheet. If you're used to using the docker command-line tool, kubectl for Docker Users explains some equivalent commands for Kubernetes.

有关安装说明,请参见安装kubectl;有关快速指南,请参阅备忘单。如果您习惯于使用docker命令行工具,kubectl for docker Users会为Kubernetes解释一些等效的命令。

 

Syntax(语法)

Use the following syntax to run kubectl commands from your terminal window:

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

where commandTYPENAME, and flags are:

  • command: Specifies the operation that you want to perform on one or more resources, for example creategetdescribedelete.

  • TYPE: Specifies the resource type. Resource types are case-insensitive and you can specify the singular, plural, or abbreviated forms. For example, the following commands produce the same output:

    指定资源类型。资源类型不区分大小写,可以指定单数、复数或缩写形式。例如,以下命令产生相同的输出:

     [root@aozhejin ~]# kubectl get pods
     NAME READY STATUS RESTARTS AGE
     cks-node-0 1/1 Running 0 8d
     cps-node-0 1/1 Running 0 71d
     fyk-node-0 1/1 Running 0 71d
      以下命令结果一致:
      kubectl get pod pod1
      kubectl get pods pod1
      kubectl get po pod1

  • NAME: Specifies the name of the resource. Names are case-sensitive. If the name is omitted, details for all resources are displayed, for example kubectl get pods.

  • 指定资源的名称。name区分大小写。如果省略name,则会显示所有资源的详细信息,例如 kubectl get pods
    例如:省略之后pods之后命令为kubectl get (只要你记住kubectl get 命令即可,回车会提示)

    [root@aozhejin k8s]# kubectl get
     You must specify the type of resource to get. Valid resource types include:

    * all
    * certificatesigningrequests (aka 'csr')
    * clusterrolebindings
    * clusterroles
    * componentstatuses (aka 'cs')
    * configmaps (aka 'cm')
    * controllerrevisions
    * cronjobs
    * customresourcedefinition (aka 'crd')
    * daemonsets (aka 'ds')
    * deployments (aka 'deploy')
    * endpoints (aka 'ep')
    * events (aka 'ev')
    * horizontalpodautoscalers (aka 'hpa')
    * ingresses (aka 'ing')
    * jobs
    * limitranges (aka 'limits')
    * namespaces (aka 'ns')
    * networkpolicies (aka 'netpol')
    * nodes (aka 'no')
    * persistentvolumeclaims (aka 'pvc')
    * persistentvolumes (aka 'pv')
    * poddisruptionbudgets (aka 'pdb')
    * podpreset
    * pods (aka 'po')
    * podsecuritypolicies (aka 'psp')
    * podtemplates
    * replicasets (aka 'rs')
    * replicationcontrollers (aka 'rc')
    * resourcequotas (aka 'quota')
    * rolebindings
    * roles
    * secrets
    * serviceaccounts (aka 'sa')
    * services (aka 'svc')
    * statefulsets (aka 'sts')
    * storageclasses (aka 'sc')error: Required resource not specified.
    Use "kubectl explain <resource>" for a detailed description of that resource (e.g. kubectl explain pods).
    See 'kubectl get -h' for help and examples.

  • When performing an operation on multiple resources, you can specify each resource by type and name or specify one or more files

    • To specify resources by type and name:

      • To group resources if they are all the same type: TYPE1 name1 name2 name<#>.
        Example: kubectl get pod example-pod1 example-pod2(指定显示多个具体pod信息)

      • To specify multiple resource types individually: TYPE1/name1 TYPE1/name2 TYPE2/name3 TYPE<#>/name<#>.
        Example: kubectl get pod/example-pod1 replicationcontroller/example-rc1

    • To specify resources with one or more files: -f file1 -f file2 -f file<#>

      • Use YAML rather than JSON since YAML tends to be more user-friendly, especially for configuration files.
        Example: kubectl get -f ./pod.yaml
  • flags: Specifies optional flags. For example, you can use the -s or --server flags to specify the address and port of the Kubernetes API server.

Caution: Flags that you specify from the command line override default values and any corresponding environment variables.

If you need help, run kubectl help from the terminal window.
   

[root@aozhejin ~]# 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
run-container Run a particular image on the cluster. This command is deprecated, use "run" instead

Basic Commands (Intermediate):
get Display one or many resources
explain Documentation of 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
rolling-update Perform a rolling update of the given ReplicationController
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:
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
convert Convert config files between different API versions

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-versions Print the supported API versions on the server, in the form of "group/version"
config Modify kubeconfig files
help Help about any command
plugin Runs a command-line plugin
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).

In-cluster authentication and namespace overrides
集群内身份验证和命名空间覆盖

默认情况下,kubectl将首先确定它是否在pod内运行,从而在集群中运行。

It starts by checking for the KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT environment variables and the existence of a service account token file at /var/run/secrets/kubernetes.io/serviceaccount/token. If all three are found in-cluster authentication is assumed.

它首先检查KUBERNETES_SERVICE_主机和KUBERNETES_SERVICE_端口环境变量,以及/var/run/secrets/io/serviceaccount/token 
KUBERNETES处是否存在服务帐户令牌文件。如果这三个都在集群中找到,则假定进行身份验证。

To maintain backwards compatibility, if the POD_NAMESPACE environment variable is set during in-cluster authentication it will override the default namespace from the service account token. Any manifests or tools relying on namespace defaulting will be affected by this.

为了保持向后兼容性,如果在集群内身份验证期间设置了POD_NAMESPACE环境变量,它将覆盖服务帐户令牌中的默认名称空间。任何依赖命名空间默认设置的清单或工具都将受到此影响。

POD_NAMESPACE environment variable(POD_NAMESPACE环境变量)

If the POD_NAMESPACE environment variable is set, cli operations on namespaced resources will default to the variable value.

 如果设置了POD_NAMESPACE 环境变量,则命名空间资源上的cli操作将默认为变量值

For example, if the variable is set to seattlekubectl get pods would return pods in the seattle namespace.

例如,如果POD_NAMESPACE 变量设置为seattle,kubectl get pods将返回seattle名称空间中的pods。

This is because pods are a namespaced resource, and no namespace was provided in the command. Review the output of kubectl api-resources to determine if a resource is namespaced.

Explicit use of --namespace <value> overrides this behavior.

显式使用 --namespace<value> 覆盖此行为。(覆盖POD_NAMESPACE变量设置)

 

kubectl 怎么处理 ServiceAccount tokens

kubectl如何处理ServiceAccount tokens

If:

  • there is Kubernetes service account token file mounted at /var/run/secrets/kubernetes.io/serviceaccount/token, and
  • the KUBERNETES_SERVICE_HOST environment variable is set, and
  • the KUBERNETES_SERVICE_PORT environment variable is set, and
  • you don't explicitly specify a namespace on the kubectl command line  then kubectl assumes it is running in your cluster.
在kubectl命令行上没有显式指定名称空间,然后kubectl假设它正在集群中运行。

The kubectl tool looks up the namespace of that ServiceAccount (this is the same as the namespace of the Pod) and acts against that namespace.

kubectl工具查找该ServiceAccount的名称空间(这与Pod的名称空间相同),并针对该名称空间进行操作。

This is different from what happens outside of a cluster; when kubectl runs outside a cluster and you don't specify a namespace, the kubectl command acts against the default namespace.

这与集群之外发生的情况不同;当kubectl在集群之外运行时,您没有指定名称空间,kubectl命令会对默认名称空间执行操作。

操作

下表包括所有kubectl操作的简短描述和通用语法

选项语法描述
alpha kubectl alpha SUBCOMMAND [flags]

List the available commands that correspond to alpha features, which are not enabled in Kubernetes clusters by default.

列出与alpha功能相对应的可用功能,默认情况下,Kubernetes群集不会启用这些功能。

annotate kubectl annotate (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]

Add or update the annotations of one or more resources.

添加或更新一个或多个资源的注释。

api-resources kubectl api-resources [flags]

List the API resources that are available.列出可用的API资源。

1.11版本之后支持

api-versions kubectl api-versions [flags]

List the API versions that are available.

列出可用的API版本(组名和可用的版本号,注意没有在这个列表中的组名,组版本不可用)

[root@aozhejin ~]# kubectl api-versions
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
apps/v1beta1
apps/v1beta2
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
batch/v1
batch/v1beta1
certificates.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
management.cattle.io/v3
monitoring.coreos.com/v1
networking.k8s.io/v1
policy/v1beta1
project.cattle.io/v3
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

apply kubectl apply -f FILENAME [flags] Apply a configuration change to a resource from a file or stdin.
将配置更改应用于文件或stdin中的资源。
attach kubectl attach POD -c CONTAINER [-i] [-t] [flags] Attach to a running container either to view the output stream or interact with the container (stdin).
连接到正在运行的容器以查看输出流或与容器交互(stdin)。
auth kubectl auth [flags] [options] Inspect authorization.
检查授权。
autoscale kubectl autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags] Automatically scale the set of pods that are managed by a replication controller.
自动缩放由复制控制器管理的POD集。
certificate kubectl certificate SUBCOMMAND [options] Modify certificate resources.
修改证书资源。
cluster-info kubectl cluster-info [flags] Display endpoint information about the master and services in the cluster.
显示群集中主机和服务的端点信息。
 

[root@aozhejin ~]# kubectl cluster-info 
Kubernetes master is running at http://localhost:8080
nginx is running at http://localhost:8080/api/v1/namespaces/kube-system/services/efk-server:efk/proxy
Heapster is running at http://localhost:8080/api/v1/namespaces/kube-system/services/heapster/proxy
CoreDNS is running at http://localhost:8080/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
monitoring-grafana is running at http://localhost:8080/api/v1/namespaces/kube-system/services/monitoring-grafana/proxy
monitoring-influxdb is running at http://localhost:8080/api/v1/namespaces/kube-system/services/monitoring-influxdb/proxy
registry is running at http://localhost:8080/api/v1/namespaces/kube-system/services/registry:http/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

completion kubectl completion SHELL [options] Output shell completion code for the specified shell (bash or zsh).
为指定的shell(bash或zsh)输出shell完成代码。
config kubectl config SUBCOMMAND [flags] Modifies kubeconfig files. See the individual subcommands for details.
修改kubeconfig文件。有关详细信息,请参见各个子命令。
convert kubectl convert -f FILENAME [options] Convert config files between different API versions. Both YAML and JSON formats are accepted. Note - requires kubectl-convert plugin to be installed.
在不同的API版本之间转换配置文件。YAML和JSON格式都可以接受。注意-需要安装kubectl convert插件。
cordon kubectl cordon NODE [options] Mark node as unschedulable.
将node节点标记为不可调度。
cp kubectl cp <file-spec-src> <file-spec-dest> [options] Copy files and directories to and from containers.
从容器中复制文件和目录(到本地)。
create kubectl create -f FILENAME [flags] Create one or more resources from a file or stdin.
从文件或stdin创建一个或多个资源。
delete kubectl delete (-f FILENAME | TYPE [NAME | /NAME | -l label | --all]) [flags] Delete resources either from a file, stdin, or specifying label selectors, names, resource selectors, or resources.
从文件、stdin或指定标签选择器、名称、资源选择器或资源中删除资源。
describe kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | /NAME | -l label]) [flags] Display the detailed state of one or more resources.
显示一个或多个资源的详细状态。(这个命令很管用,特别是排查错误的时候)
diff kubectl diff -f FILENAME [flags] Diff file or stdin against live configuration.
Diff文件或stdin与实时配置相对应。
drain kubectl drain NODE [options] Drain node in preparation for maintenance.
驱散节点(上的pod),为维护做好准备。
edit kubectl edit (-f FILENAME | TYPE NAME | TYPE/NAME) [flags] Edit and update the definition of one or more resources on the server by using the default editor.
使用默认编辑器编辑和更新服务器上一个或多个资源的定义。
exec kubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [-- COMMAND [args...]] Execute a command against a container in a pod.
在pod中,执行容器的命令。(在master操作,执行某个pod里面的某个容器内的命令)
explain kubectl explain [--recursive=false] [flags] Get documentation of various resources. For instance pods, nodes, services, etc.
获取各种资源的文档。例如pod、node、service等。
expose kubectl expose (-f FILENAME | TYPE NAME | TYPE/NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type] [flags] Expose a replication controller, service, or pod as a new Kubernetes service.
将 replication controller, service, 或 pod 暴露成为一个新的Kubernetes服务。
get kubectl get (-f FILENAME | TYPE [NAME | /NAME | -l label]) [--watch] [--sort-by=FIELD] [[-o | --output]=OUTPUT_FORMAT] [flags] List one or more resources.
列出一个或多个资源。
 

获取所有pod的详细信息:
kubectl get pod/ kubectl get po/kubectl get pods
获取所有pod的详细信息:
kubectl get po -o wide
获取所有namespace下的运行的所有pod:
[root@aozhejin ~]# kubectl get po --all-namespaces
获取所有namespace下的运行的所有pod的标签:
[root@aozhejin ~]#kubectl get po --show-labels
获取该节点的所有命名空间:
[root@aozhejin ~]#kubectl get namespace
以yaml格式输出pod的详细信息:
[root@aozhejin ~]#kubectl get po <podname> -o yaml
以json格式输出pod的详细信息:
[root@aozhejin ~]#kubectl get po <podname> -o json

kustomize kubectl kustomize <dir> [flags] [options] List a set of API resources generated from instructions in a kustomization.yaml file. The argument must be the path to the directory containing the file, or a git repository URL with a path suffix specifying same with respect to the repository root.
列出从kustomization指令生成的一组API资源(.yaml文件中)。
参数必须是包含该文件的目录的路径,或者是带有路径后缀的git存储库URL,该路径后缀针对存储库根指定相同的路径。
label kubectl label (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags] Add or update the labels of one or more resources.
添加或更新一个或多个资源的标签。(比如:给主机打标签,定向调度等)
logs kubectl logs POD [-c CONTAINER] [--follow] [flags] Print the logs for a container in a pod.
打印pod中某个容器的日志(pod和container是一对多的关系)。
options kubectl options List of global command-line options, which apply to all commands.
适用于所有命令的全局命令行选项列表。
patch kubectl patch (-f FILENAME | TYPE NAME | TYPE/NAME) --patch PATCH [flags] Update one or more fields of a resource by using the strategic merge patch process.
使用策略合并补丁程序更新资源的一个或多个字段。
plugin kubectl plugin [flags] [options] Provides utilities for interacting with plugins.
提供与插件交互的实用程序
port-forward kubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N] [flags] Forward one or more local ports to a pod.
将一个或多个本地端口转发到pod。
proxy kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [flags] Run a proxy to the Kubernetes API server.
运行Kubernetes API server的代理。
replace kubectl replace -f FILENAME Replace a resource from a file or stdin.
从文件或stdin中替换资源。
rollout kubectl rollout SUBCOMMAND [options] Manage the rollout of a resource. Valid resource types include: deployments, daemonsets and statefulsets.
管理资源的展开。有效的资源类型包括:部署、守护程序集和状态集
run kubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-run=server|client|none] [--overrides=inline-json] [flags] Run a specified image on the cluster.
在集群上运行指定的映像。
scale kubectl scale (-f FILENAME | TYPE NAME | TYPE/NAME) --replicas=COUNT [--resource-version=version] [--current-replicas=count] [flags] Update the size of the specified replication controller.
更新指定复制控制器的大小。
set kubectl set SUBCOMMAND [options] Configure application resources.
配置应用程序资源。
taint kubectl taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ... KEY_N=VAL_N:TAINT_EFFECT_N [options] Update the taints on one or more nodes.
更新一个或多个节点上的污染
top kubectl top [flags] [options] Display Resource (CPU/Memory/Storage) usage.
显示资源(CPU/内存/存储)使用情况
uncordon kubectl uncordon NODE [options] Mark node as schedulable.
将node节点标记为可调度。
version kubectl version [--client] [flags] Display the Kubernetes version running on the client and server.
显示在client和server上运行的Kubernetes版本
wait kubectl wait ([-f FILENAME] | resource.group/resource.name | resource.group [(-l label | --all)]) [--for=delete|--for condition=available] [options] Experimental: Wait for a specific condition on one or many resources.
实验性:等待一个或多个资源的特定条件
kubectl 命令选项 举例:
[root@aozhejin k8s]# kubectl options
The following options can be passed to any command: 以下的(参数)选项可以被传递给任何命令

      --allow-verification-with-non-compliant-keys=false: Allow a SignatureVerifier to use keys which are technically
non-compliant with RFC6962.
      --alsologtostderr=false: log to standard error as well as files
      --application-metrics-count-limit=100: Max number of application metrics to store (per container)
      --as='': Username to impersonate for the operation
      --as-group=[]: Group to impersonate for the operation, this flag can be repeated to specify multiple groups.
      --azure-container-registry-config='': Path to the file containing Azure container registry configuration
information.
      --boot-id-file='/proc/sys/kernel/random/boot_id': Comma-separated list of files to check for boot-id. Use the
first one that exists.
      --cache-dir='/root/.kube/http-cache': Default HTTP cache directory
      --certificate-authority='': Path to a cert file for the certificate authority
      --client-certificate='': Path to a client certificate file for TLS
      --client-key='': Path to a client key file for TLS
      --cloud-provider-gce-lb-src-cidrs=130.211.0.0/22,209.85.152.0/22,209.85.204.0/22,35.191.0.0/16: CIDRs opened in
GCE firewall for LB traffic proxy & health checks
      --cluster='': The name of the kubeconfig cluster to use
      --container-hints='/etc/cadvisor/container_hints.json': location of the container hints file
      --containerd='unix:///var/run/containerd.sock': containerd endpoint
      --context='': The name of the kubeconfig context to use
      --default-not-ready-toleration-seconds=300: Indicates the tolerationSeconds of the toleration for
notReady:NoExecute that is added by default to every pod that does not already have such a toleration.
      --default-unreachable-toleration-seconds=300: Indicates the tolerationSeconds of the toleration for
unreachable:NoExecute that is added by default to every pod that does not already have such a toleration.
      --docker='unix:///var/run/docker.sock': docker endpoint
      --docker-env-metadata-whitelist='': a comma-separated list of environment variable keys that needs to be collected
for docker containers
      --docker-only=false: Only report docker containers in addition to root stats
      --docker-root='/var/lib/docker': DEPRECATED: docker root is read from docker info (this is a fallback, default:
/var/lib/docker)
      --docker-tls=false: use TLS to connect to docker
      --docker-tls-ca='ca.pem': path to trusted CA
      --docker-tls-cert='cert.pem': path to client certificate
      --docker-tls-key='key.pem': path to private key
      --enable-load-reader=false: Whether to enable cpu load reader
      --event-storage-age-limit='default=0': Max length of time for which to store events (per type). Value is a comma
separated list of key values, where the keys are event types (e.g.: creation, oom) or "default" and the value is a
duration. Default is applied to all non-specified event types
      --event-storage-event-limit='default=0': Max number of events to store (per type). Value is a comma separated list
of key values, where the keys are event types (e.g.: creation, oom) or "default" and the value is an integer. Default is
applied to all non-specified event types
      --global-housekeeping-interval=1m0s: Interval between global housekeepings
      --housekeeping-interval=10s: Interval between container housekeepings
      --insecure-skip-tls-verify=false: If true, the server's certificate will not be checked for validity. This will
make your HTTPS connections insecure
      --ir-data-source='influxdb': Data source used by InitialResources. Supported options: influxdb, gcm.
      --ir-dbname='k8s': InfluxDB database name which contains metrics required by InitialResources
      --ir-hawkular='': Hawkular configuration URL
      --ir-influxdb-host='localhost:8080/api/v1/namespaces/kube-system/services/monitoring-influxdb:api/proxy': Address
of InfluxDB which contains metrics required by InitialResources
      --ir-namespace-only=false: Whether the estimation should be made only based on data from the same namespace.
      --ir-password='root': Password used for connecting to InfluxDB
      --ir-percentile=90: Which percentile of samples should InitialResources use when estimating resources. For
experiment purposes.
      --ir-user='root': User used for connecting to InfluxDB
      --kubeconfig='': Path to the kubeconfig file to use for CLI requests.
      --log-backtrace-at=:0: when logging hits line file:N, emit a stack trace
      --log-cadvisor-usage=false: Whether to log the usage of the cAdvisor container
      --log-dir='': If non-empty, write log files in this directory
      --log-flush-frequency=5s: Maximum number of seconds between log flushes
      --loglevel=1: Log level (0 = DEBUG, 5 = FATAL)
      --logtostderr=true: log to standard error instead of files
      --machine-id-file='/etc/machine-id,/var/lib/dbus/machine-id': Comma-separated list of files to check for
machine-id. Use the first one that exists.
      --match-server-version=false: Require server version to match client version
  -n, --namespace='': If present, the namespace scope for this CLI request
      --password='': Password for basic authentication to the API server
      --request-timeout='0': The length of time to wait before giving up on a single server request. Non-zero values
should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests.
  -s, --server='': The address and port of the Kubernetes API server
      --stderrthreshold=2: logs at or above this threshold go to stderr
      --storage-driver-buffer-duration=1m0s: Writes in the storage driver will be buffered for this duration, and
committed to the non memory backends as a single transaction
      --storage-driver-db='cadvisor': database name
      --storage-driver-host='localhost:8086': database host:port
      --storage-driver-password='root': database password
      --storage-driver-secure=false: use secure connection with database
      --storage-driver-table='stats': table name
      --storage-driver-user='root': database username
      --token='': Bearer token for authentication to the API server
      --user='': The name of the kubeconfig user to use
      --username='': Username for basic authentication to the API server
  -v, --v=0: log level for V logs
      --version=false: Print version information and quit
      --vmodule=: comma-separated list of pattern=N settings for file-filtered logging

 

学习更多的选项命令请参看  kubectl 文档.

具体命令还可以查看 https://kubernetes.io/docs/reference/kubectl/kubectl/

我们也看看这里

  • kubectl annotate - Update the annotations on a resource 更新资源上的注释
  • kubectl api-resources - Print the supported API resources on the server 在服务器上打印支持的API资源(1.11之后支持)
  • kubectl api-versions - Print the supported API versions on the server, in the form of "group/version" 在服务器上以“组/版本”的形式打印支持的API版本
  • kubectl apply - Apply a configuration to a resource by filename or stdin 按文件名或stdin对资源应用配置
  • kubectl attach - Attach to a running container 连接到一个正在运行的容器上
  • kubectl auth - Inspect authorization 检查授权
  • kubectl autoscale - Auto-scale a Deployment, ReplicaSet, or ReplicationController 自动缩放Deployment, ReplicaSet, 和ReplicationController
  • kubectl certificate - Modify certificate resources. 修改证书资源
  • kubectl cluster-info - Display cluster info 显示集群信息
  • kubectl completion - Output shell completion code for the specified shell (bash or zsh)
  • kubectl config - Modify kubeconfig files 修改kubeconfig文件
  • kubectl cordon - Mark node as unschedulable 将node节点标记为不可调度
  • kubectl cp - Copy files and directories to and from containers.从容器中复制文件和目录(到宿主机)。
  • kubectl create - Create a resource from a file or from stdin. 从文件或stdin创建资源。
  • kubectl debug - Create debugging sessions for troubleshooting workloads and nodes 创建调试会话以对工作负载和节点进行故障排除
  • kubectl delete - Delete resources by filenames, stdin, resources and names, or by resources and label selector
  • kubectl describe - Show details of a specific resource or group of resources 显示特定资源或资源组的详细信息(排查错误的时候很有用)
  • kubectl diff - Diff live version against would-be applied version 区分实时版本和潜在应用版本
  • kubectl drain - Drain node in preparation for maintenance 驱散节点(上的pod)准备进行维护
  • kubectl edit - Edit a resource on the server 在服务器上编辑资源(编辑yaml文件等)
  • kubectl exec - Execute a command in a container  在容器中执行命令(在master上可以通过kubeclt exec -ti ..... 命令直接执行某容器中的命令)
  • kubectl explain - Documentation of resources  解释资源(例如: kubectl explain pod,  kubectl explain  pod.spec等)
  • kubectl expose - Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service
  • kubectl get - Display one or many resources 显示一个或多个资源
  • kubectl kustomize - Build a kustomization target from a directory or a remote url. 从目录或远程url构建kustomization目标。
  • kubectl label     - Update the labels on a resource 更新资源上的标签
  • kubectl logs      - Print the logs for a container in a pod 打印pod中容器的日志
  • kubectl options - Print the list of flags inherited by all commands 打印所有命令继承的标志列表
  • kubectl patch    - Update field(s) of a resource 更新资源的字段
  • kubectl plugin   - Provides utilities for interacting with plugins. 提供与插件交互的实用程序。
  • kubectl port-forward - Forward one or more local ports to a pod 将一个或多个本地端口转发到pod
  • kubectl proxy            - Run a proxy to the Kubernetes API server 运行Kubernetes API服务器的代理
  • kubectl replace         - Replace a resource by filename or stdin 用文件名或stdin替换资源
  • kubectl rollout           - Manage the rollout of a resource            管理资源的展开
  • kubectl run                - Run a particular image on the cluster    在集群上运行特定映像
  • kubectl scale            - Set a new size for a Deployment, ReplicaSet or Replication Controller
  • kubectl set                - Set specific features on objects 在对象上设置特定功能
  • kubectl taint              - Update the taints on one or more nodes 更新一个或多个节点上的污染
  • kubectl top               - Display Resource (CPU/Memory/Storage) usage. 显示资源(CPU/内存/存储)使用情况
  • kubectl uncordon     - Mark node as schedulable 将node节点标记为可调度
  • kubectl version        - Print the client and server version information 打印客户端和服务器版本信息
  • kubectl wait             - Experimental: Wait for a specific condition on one or many resources.

资源类型

下表列出了所有受支持的资源类型及其缩写别名(短名称)。

(This output can be retrieved from kubectl api-resources, 该命令1.11版本之后支持 and was accurate as of Kubernetes 1.19.1.)

NAME短名称APIGROUPNAMESPACEDKIND
bindings    无组 true Binding
componentstatuses cs  无组  false ComponentStatus

举例:
[root@aozhejin ~]# kubectl get cs
NAME STATUS MESSAGE ERROR
scheduler Healthy ok
controller-manager Healthy ok
etcd-1 Healthy {"health": "true"}
etcd-2 Healthy {"health": "true"}
etcd-0 Healthy {"health": "true"}

configmaps cm  无组  true ConfigMap
endpoints ep  无组  true Endpoints
events ev  无组  true Event
limitranges limits  无组  true LimitRange
namespaces ns  无组  false Namespace
nodes no  无组  false Node
persistentvolumeclaims pvc  无组  true PersistentVolumeClaim
persistentvolumes pv  无组  false PersistentVolume
pods po  无组  true Pod
podtemplates     true PodTemplate
replicationcontrollers rc  无组  true ReplicationController
resourcequotas quota  无组  true ResourceQuota
secrets     true Secret
serviceaccounts sa  无组  true ServiceAccount
services svc  无组  true Service
mutatingwebhookconfigurations   admissionregistration.k8s.io false MutatingWebhookConfiguration
validatingwebhookconfigurations   admissionregistration.k8s.io false ValidatingWebhookConfiguration
customresourcedefinitions crd,crds apiextensions.k8s.io false CustomResourceDefinition
apiservices   apiregistration.k8s.io false APIService
controllerrevisions   apps true ControllerRevision
daemonsets ds apps true DaemonSet
deployments deploy apps true Deployment
replicasets rs apps true ReplicaSet
statefulsets sts apps true StatefulSet
tokenreviews   authentication.k8s.io false TokenReview
localsubjectaccessreviews   authorization.k8s.io true LocalSubjectAccessReview
selfsubjectaccessreviews   authorization.k8s.io false SelfSubjectAccessReview
selfsubjectrulesreviews   authorization.k8s.io false SelfSubjectRulesReview
subjectaccessreviews   authorization.k8s.io false SubjectAccessReview
horizontalpodautoscalers hpa autoscaling true HorizontalPodAutoscaler
cronjobs cj batch true CronJob
jobs   batch true Job
certificatesigningrequests csr certificates.k8s.io false CertificateSigningRequest
leases   coordination.k8s.io true Lease
endpointslices   discovery.k8s.io true EndpointSlice
events ev events.k8s.io true Event
ingresses ing extensions true Ingress
flowschemas   flowcontrol.apiserver.k8s.io false FlowSchema
prioritylevelconfigurations   flowcontrol.apiserver.k8s.io false PriorityLevelConfiguration
ingressclasses   networking.k8s.io false IngressClass
ingresses ing networking.k8s.io true Ingress
networkpolicies netpol networking.k8s.io true NetworkPolicy
runtimeclasses   node.k8s.io false RuntimeClass
poddisruptionbudgets pdb policy true PodDisruptionBudget
podsecuritypolicies psp policy false PodSecurityPolicy
clusterrolebindings   rbac.authorization.k8s.io false ClusterRoleBinding
clusterroles   rbac.authorization.k8s.io false ClusterRole
rolebindings   rbac.authorization.k8s.io true RoleBinding
roles   rbac.authorization.k8s.io true Role
priorityclasses pc scheduling.k8s.io false PriorityClass
csidrivers   storage.k8s.io false CSIDriver
csinodes   storage.k8s.io false CSINode
storageclasses sc storage.k8s.io false StorageClass
volumeattachments   storage.k8s.io false VolumeAttachment

短名称举例:

[root@aozhejin k8s]# kubectl get rc
[root@aozhejin k8s]# kubectl get ns
[root@aozhejin k8s]# kubectl get sts
[root@aozhejin k8s]# kubectl get cj
[root@aozhejin k8s]# kubectl get ing
[root@aozhejin k8s]# kubectl get pc

输出选项

Use the following sections for information about how you can format or sort the output of certain commands. For details about which commands support the various output options, see the kubectl reference documentation.

格式输出

The default output format for all kubectl commands is the human readable plain-text format. To output details to your terminal window in a specific format, you can add either the -o or --output flags to a supported kubectl command.

语法

kubectl [command] [TYPE] [NAME] -o <output_format>

kubectl 选项操作,支持以下的格式输出

输出格式描述
-o custom-columns=<spec> Print a table using a comma separated list of custom columns.
-o custom-columns-file=<filename> Print a table using the custom columns template in the <filename> file.
-o json Output a JSON formatted API object.
-o jsonpath=<template> Print the fields defined in a jsonpath expression.
-o jsonpath-file=<filename> Print the fields defined by the jsonpath expression in the <filename> file.
-o name Print only the resource name and nothing else.
-o wide Output in the plain-text format with any additional information. For pods, the node name is included.
-o yaml Output a YAML formatted API object.
例如

下面的命令输出 YAML 格式 object:

kubectl get pod mypodname -o yaml

Remember: See the kubectl reference documentation for details about which output format is supported by each command.

自定义列

To define custom columns and output only the details that you want into a table, you can use the custom-columns option. You can choose to define the custom columns inline or use a template file: -o custom-columns=<spec> or -o custom-columns-file=<filename>.

 样例: 

Inline:

kubectl get pods <pod-name> -o custom-columns=NAME:.metadata.name,RSRC:.metadata.resourceVersion

模板文件:

kubectl get pods <pod-name> -o custom-columns-file=template.txt

where the template.txt file contains:

NAME          RSRC
metadata.name metadata.resourceVersion

The result of running either command is similar to:

NAME           RSRC
submit-queue   610995

Server-side columns

kubectl supports receiving specific column information from the server about objects. This means that for any given resource, the server will return columns and rows relevant to that resource, for the client to print. This allows for consistent human-readable output across clients used against the same cluster, by having the server encapsulate the details of printing.

This feature is enabled by default. To disable it, add the --server-print=false flag to the kubectl get command.

 样例

To print information about the status of a pod, use a command like the following:

kubectl get pods <pod-name> --server-print=false

输出如下:

NAME       AGE
pod-name   1m

Sorting list objects

To output objects to a sorted list in your terminal window, you can add the --sort-by flag to a supported kubectl command. Sort your objects by specifying any numeric or string field with the --sort-by flag. To specify a field, use a jsonpath expression.

语法

kubectl [command] [TYPE] [NAME] --sort-by=<jsonpath_exp>
样例

To print a list of pods sorted by name, you run:

kubectl get pods --sort-by=.metadata.name

例子: 通用操作

Use the following set of examples to help you familiarize yourself with running the commonly used kubectl operations:

kubectl apply - Apply or Update a resource from a file or stdin.

# Create a service using the definition in example-service.yaml.
kubectl apply -f example-service.yaml

# Create a replication controller using the definition in example-controller.yaml.
kubectl apply -f example-controller.yaml

# Create the objects that are defined in any .yaml, .yml, or .json file within the <directory> directory.
kubectl apply -f <directory>

kubectl get - List one or more resources.

# List all pods in plain-text output format.
kubectl get pods

# List all pods in plain-text output format and include additional information (such as node name).
kubectl get pods -o wide

# List the replication controller with the specified name in plain-text output format. Tip: You can shorten and replace the 'replicationcontroller' resource type with the alias 'rc'.
kubectl get replicationcontroller <rc-name>

# List all replication controllers and services together in plain-text output format.
kubectl get rc,services

# List all daemon sets in plain-text output format.
kubectl get ds

# List all pods running on node server01
kubectl get pods --field-selector=spec.nodeName=server01

kubectl describe - Display detailed state of one or more resources, including the uninitialized ones by default.

# Display the details of the node with name <node-name>.
kubectl describe nodes <node-name>

# Display the details of the pod with name <pod-name>.
kubectl describe pods/<pod-name>

# Display the details of all the pods that are managed by the replication controller named <rc-name>.
# Remember: Any pods that are created by the replication controller get prefixed with the name of the replication controller.
kubectl describe pods <rc-name>

# Describe all pods
kubectl describe pods
提示: The kubectl get command is usually used for retrieving one or more resources of the same resource type. It features a rich set of flags that allows you to customize the output format using the -o or --output flag, for example. You can specify the -w or --watch flag to start watching updates to a particular object. The kubectl describe command is more focused on describing the many related aspects of a specified resource. It may invoke several API calls to the API server to build a view for the user. For example, the kubectl describe node command retrieves not only the information about the node, but also a summary of the pods running on it, the events generated for the node etc.

kubectl delete - Delete resources either from a file, stdin, or specifying label selectors, names, resource selectors, or resources.

# Delete a pod using the type and name specified in the pod.yaml file.
kubectl delete -f pod.yaml

# Delete all the pods and services that have the label '<label-key>=<label-value>'.
kubectl delete pods,services -l <label-key>=<label-value>

# Delete all pods, including uninitialized ones.
kubectl delete pods --all

kubectl exec - Execute a command against a container in a pod.

# Get output from running 'date' from pod <pod-name>. By default, output is from the first container.
kubectl exec <pod-name> -- date

# Get output from running 'date' in container <container-name> of pod <pod-name>.
kubectl exec <pod-name> -c <container-name> -- date

# Get an interactive TTY and run /bin/bash from pod <pod-name>. By default, output is from the first container.
kubectl exec -ti <pod-name> -- /bin/bash

kubectl logs - Print the logs for a container in a pod.

# Return a snapshot of the logs from pod <pod-name>.
kubectl logs <pod-name>

# Start streaming the logs from pod <pod-name>. This is similar to the 'tail -f' Linux command.
kubectl logs -f <pod-name>

kubectl diff - View a diff of the proposed updates to a cluster.

# Diff resources included in "pod.json".
kubectl diff -f pod.json

# Diff file read from stdin.
cat service.yaml | kubectl diff -f -

 创建和使用 plugins --- k8s kubectl 插件编写(k8s 1.14版本之后支持扩展kubectl命令)

如果你想写自己的kubectl ....相关命令,
可以参看 https://www.cnblogs.com/aozhejin/p/17987061

 Use the following set of examples to help you familiarize yourself with writing and using kubectl plugins:

# create a simple plugin in any language and name the resulting executable file
# so that it begins with the prefix "kubectl-"  
cat ./kubectl-hello
#!/bin/sh
# this plugin prints the words "hello world"
echo "hello world"

  让我们来运行一下kubectl 插件

chmod a+x ./kubectl-hello

# and move it to a location in our PATH
sudo mv ./kubectl-hello /usr/local/bin
sudo chown root:root /usr/local/bin

# You have now created and "installed" a kubectl plugin.
# You can begin using this plugin by invoking it from kubectl as if it were a regular command
kubectl hello
hello world
# You can "uninstall" a plugin, by removing it from the folder in your
# $PATH where you placed it
sudo rm /usr/local/bin/kubectl-hello

In order to view all of the plugins that are available to kubectl, use the kubectl plugin list subcommand:

kubectl plugin list

如下输出:

The following kubectl-compatible plugins are available:

/usr/local/bin/kubectl-hello
/usr/local/bin/kubectl-foo
/usr/local/bin/kubectl-bar

kubectl plugin list also warns you about plugins that are not executable, or that are shadowed by other plugins; for example:

chmod -x /usr/local/bin/kubectl-foo # remove execute permission
kubectl plugin list
The following kubectl-compatible plugins are available:

/usr/local/bin/kubectl-hello
/usr/local/bin/kubectl-foo
  - warning: /usr/local/bin/kubectl-foo identified as a plugin, but it is not executable
/usr/local/bin/kubectl-bar

error: one plugin warning was found

You can think of plugins as a means to build more complex functionality on top of the existing kubectl commands:

cat ./kubectl-whoami

The next few examples assume that you already made kubectl-whoami have the following contents:

#!/bin/bash

# this plugin makes use of the `kubectl config` command in order to output
# information about the current user, based on the currently selected context
kubectl config view --template='{{ range .contexts }}{{ if eq .name "'$(kubectl config current-context)'" }}Current user: {{ printf "%s\n" .context.user }}{{ end }}{{ end }}'

 Running the above command gives you an output containing the user for the current context in your KUBECONFIG file:

# make the file executable
chmod +x ./kubectl-whoami

# and move it into your PATH
mv ./kubectl-whoami /usr/local/bin

kubectl whoami
Current user: plugins-user

   What's next

posted @ 2022-05-10 21:36  jinzi  阅读(23)  评论(0编辑  收藏  举报