Kubectl 命令参考

Kubectl 是和 kubernetes 集群交互的命令行工具。 kubectl 会使用 $HOME/.kube/config 文件作为默认配置(也就是 kubeconfig)。我们可以通过设置环境变量 KUBECONFIG 或命令行选项 --kubeconfig 来指定 kubeconfig。

本文概述kubectl语法,介绍命令操作,并提供常见的示例。有关每个命令的详细信息,包括所有支持的 falgs 和子命令,请参阅kubectl参考文档 。有关安装说明,请参阅安装kubectl

语法

命令行使用可以总结为如下语法:

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

解释如下:

  • command 指定对一个或多个资源的操作,如 creategetdescribedelete

  • TYPE 指明了要操作的资源类型。资源类型不区分大小写,可以使用单数、复数、缩写形式(注意,缩写是严格的,不能单复数大小写)。比如,如下几条命令有相同的输出:

    1
    2
    3
    kubectl get pod pod1
    kubectl get pods pod1
    kubectl get po pod1
  • NAME 指明资源名称。名称区分大小写,如果省略了资源名称,则展示此类所有资源的详情。如 kubectl get pods

在对多个资源应用一个操作的时候,可以按照资源的类型和名称分别指定每个资源,或指定一个或多个文件:

  • 通过类型和名称:
    • 同一个类型分组: TYPE1 name1 name2 name<#>
      如: kubectl get pod example-pod1 example-pod2
    • 具有不同类型的多个资源: TYPE1/name1 TYPE1/name2 TYPE2/name3 TYPE<#>/name<#>
      如: kubectl get pod/example-pod1 replicationcontroller/example-rc1
  • 通过一个或多个文件指定资源: -f file1 -f file2 -f file<#>
    • 文件使用YAML格式而不是JSON格式。因为YAML对用户更友好,尤其是配置文件
      如: kubectl get pod -f ./pod.yaml

      注意:命令行指定的 flags 优先级最高,会覆盖默认值和对应的环境变量

如果需要查看帮助,使用 kubectl help 命令。

操作

下表包含所有 kubectl 操作的简短描述和通常的语法结构:(TODO: 官方表格命令过期,新命令未添加全,后续补充)

Operation Syntax Description
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.
添加或更新一个或多个资源的 annotations。
api-versions kubectl api-versions [flags] List the API versions that are available.
查看可用的 API 版本。
apply kubectl apply -f FILENAME [flags] Apply a configuration change to a resource from a file or 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).
attach 到运行中的容器,以查看容器输出或和容器交互。类似于 docker 的 attach 操作。
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.
对通过 replication controller 管理的 pods 进行自动的扩缩容。(使pods的负载在指定范围内。)
cluster-info kubectl cluster-info [flags] Display endpoint information about the master and services in the cluster.
展示集群 master 和服务(非K8S资源的 Service类型)的端点信息。
config kubectl config SUBCOMMAND [flags] Modifies kubeconfig files. See the individual subcommands for details.
修改 kubeconfig 配置内容。查看子命令获取更多信息。
create kubectl create -f FILENAME [flags] Create one or more resources from a file or 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.
删除资源。可以通过文件,标准输入或指定 label selectors,names,resource selectors, resources 的方式。
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 (BETA)
对比文件或标准输入与当前配置的区别。
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 的容器中执行一个命令。和 docker 的 exec 命令相似。
explain kubectl explain [--recursive=false] [flags] Get documentation of various resources. For instance pods, nodes, services, etc.
获取各种资源类型的文档,比如,pods,nodes,services 等。
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(包括 deployment),service,pod暴露为一个新的 kubernetes service。
get kubectl get (-f FILENAME | TYPE [NAME | /NAME | -l label]) [--watch] [--sort-by=FIELD] [[-o | --output]=OUTPUT_FORMAT] [flags] List one or more resources.
列出一个或多个资源。
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.
添加或更新一个或多个资源的 lables。
logs kubectl logs POD [-c CONTAINER] [--follow] [flags] Print the logs for a container in a pod.
输出pod中某个container的日志。和 docker logs 类似。
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.
更新资源的一个或多个字段。默认用策略性合并补丁(–type=’strategic’)方式。
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.
从文件或标准输入替换一个资源。
rolling-update kubectl rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE | -f NEW_CONTROLLER_SPEC) [flags] Perform a rolling update by gradually replacing the specified replication controller and its pods.
通过逐步替换 replication controller 和它的 pods 来实现一个滚动更新。(废弃了,用 rollout替代)。
run kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--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.
更新指定 replication controller 的副本数量。
stop kubectl stop Deprecated: Instead, see kubectl delete.
废弃,使用 kubectl delete 替代。
version kubectl version [--client] [flags] Display the Kubernetes version running on the client and server.
展示 Kubernetes 服务集群和本地客户端的版本。

提示:关于命令操作的更多信息参见kubectl参考文档

资源类型

The following table includes a list of all the supported resource types and their abbreviated aliases.
(This output can be retrieved from kubectl api-resources, and is accurate as of Kubernetes 1.13.3.)

Resource Name Short Names API Group Namespaced Resource Kind
componentstatuses cs false ComponentStatus
configmaps cm true ConfigMap
endpoints ep true Endpoints
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
events ev events.k8s.io true Event
ingresses ing extensions true Ingress
networkpolicies netpol networking.k8s.io true NetworkPolicy
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
storageclasses sc storage.k8s.io false StorageClass
volumeattachments storage.k8s.io false VolumeAttachment

输出选项

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.

Formatting output

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 -oor --output flags to a supported kubectl command.

Syntax

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

Depending on the kubectl operation, the following output formats are supported:

Output format Description
-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.

Example

In this example, the following command outputs the details for a single pod as a YAML formatted object:

1
kubectl get pod web-pod-13je7 -o yaml

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

Custom columns

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

Examples

Inline:

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

Template file:

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

where the template.txt file contains:

1
2
NAME          RSRC
metadata.name metadata.resourceVersion

The result of running either command is:

1
2
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 in kubectl 1.11 and higher. To disable it, add the --server-print=false flag to the kubectl get command.

Examples

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

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

Output looks like this:

1
2
NAME       READY     STATUS              RESTARTS   AGE
pod-name 1/1 Running 0 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.

Syntax

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

Example

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

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

1
2
3
4
5
6
# 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.

1
2
3
4
5
6
7
8
9
10
11
12
# 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, including uninitialized ones, in plain-text output format.
kubectl get ds --include-uninitialized
# 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.

1
2
3
4
5
6
7
8
9
# 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, not including uninitialized ones
kubectl describe pods --include-uninitialized=false

Note: 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.

1
2
3
4
5
6
7
8
# 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 name=<label-name>.
kubectl delete pods,services -l name=<label-name>
# Delete all the pods and services that have the label name=<label-name>, including uninitialized ones.
kubectl delete pods,services -l name=<label-name> --include-uninitialized
# Delete all pods, including uninitialized ones.
kubectl delete pods --all

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

1
2
3
4
5
6
# 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.

1
2
3
4
# 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>

示例:创建和使用 plugins

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

1
2
3
4
5
6
7
8
9
10
11
12
13
# 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/bash
# this plugin prints the words "hello world"
echo "hello world"
# with our plugin written, let's make it executable
sudo chmod +x ./kubectl-hello
# and move it to a location in our PATH
sudo mv ./kubectl-hello /usr/local/bin
# we have now created and "installed" a kubectl plugin.
# we can begin using our plugin by invoking it from kubectl as if it were a regular command
kubectl hello
1
hello world
1
2
# we can "uninstall" a plugin, by simply removing it from our PATH
sudo rm /usr/local/bin/kubectl-hello

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

1
kubectl plugin list
1
2
3
4
The following kubectl-compatible plugins are available:
/usr/local/bin/kubectl-hello
/usr/local/bin/kubectl-foo
/usr/local/bin/kubectl-bar
1
2
3
4
5
# this command can also warn us about plugins that are
# not executable, or that are overshadowed by other
# plugins, for example
sudo chmod -x /usr/local/bin/kubectl-foo
kubectl plugin list
1
2
3
4
5
6
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

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

1
2
3
4
5
cat ./kubectl-whoami
#!/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: {{ .context.user }}{{ end }}{{ end }}'

Running the above plugin gives us an output containing the user for the currently selected context in our KUBECONFIG file:

1
2
3
4
5
6
# make the file executable
sudo chmod +x ./kubectl-whoami
# and move it into our PATH
sudo mv ./kubectl-whoami /usr/local/bin
kubectl whoami
Current user: plugins-user

To find out more about plugins, take a look at the example cli plugin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
➜ 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

Basic Commands (Intermediate):
explain Documentation of resources
get Display one or many resources
edit Edit a resource on the server
delete Delete resources by filenames, stdin, resources and names, or by resources and label selector

Deploy Commands:
rollout Manage the rollout of a resource
scale Set a new size for a Deployment, ReplicaSet, 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:
diff Diff live version against would-be applied version
apply Apply a configuration to a resource by filename or stdin
patch Update field(s) of a resource using strategic merge patch
replace Replace a resource by filename or stdin
wait Experimental: Wait for a specific condition on one or many resources.
convert Convert config files between different API versions
kustomize Build a kustomization target from a directory or a remote url.

Settings Commands:
label Update the labels on a resource
annotate Update the annotations on a resource
completion Output shell completion code for the specified shell (bash or zsh)

Other Commands:
api-resources Print the supported API resources on the server
api-versions Print the supported API versions on the server, in the form of "group/version"
config Modify kubeconfig files
plugin Provides utilities for interacting with plugins.
version Print the client and server version information

Usage:
kubectl [flags] [options]

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).
谢谢鼓励