官网文档

1. 语法

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

  • command 操作命令,比如create, get, describe, delete

  • TYPE 指 resource type,不区分大小写,可以指定单数,复数或缩写形式

    比如下面的结果相同:

    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 指定可选标志。 例如,您可以使用-s或–server标志来指定Kubernetes API服务器的地址和端口。

注意:您在命令行中指定的标志将覆盖默认值和任何相应的环境变量。

1.1 操作命令

OperationSyntaxDescription
annotatekubectl 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-versionskubectl api-versions [flags]List the API versions that are available.
applykubectl apply -f FILENAME [flags]Apply a configuration change to a resource from a file or stdin.
attachkubectl attach POD -c CONTAINER [-i] [-t] [flags]Attach to a running container either to view the output stream or interact with the container (stdin).
autoscalekubectl 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.
cluster-infokubectl cluster-info [flags]Display endpoint information about the master and services in the cluster.
configkubectl config SUBCOMMAND [flags]Modifies kubeconfig files. See the individual subcommands for details.
createkubectl create -f FILENAME [flags]Create one or more resources from a file or stdin.
deletekubectl 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.
describekubectl describe (-f FILENAME \| TYPE [NAME_PREFIX \| /NAME \| -l label]) [flags]Display the detailed state of one or more resources.
diffkubectl diff -f FILENAME [flags]Diff file or stdin against live configuration (BETA)
editkubectl 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.
execkubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [-- COMMAND [args...]]Execute a command against a container in a pod.
explainkubectl explain [--recursive=false] [flags]Get documentation of various resources. For instance pods, nodes, services, etc.
exposekubectl 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.
getkubectl get (-f FILENAME \| TYPE [NAME \| /NAME \| -l label]) [--watch] [--sort-by=FIELD] [[-o \| --output]=OUTPUT_FORMAT] [flags]List one or more resources.
labelkubectl 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.
logskubectl logs POD [-c CONTAINER] [--follow] [flags]Print the logs for a container in a pod.
patchkubectl 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.
port-forwardkubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N] [flags]Forward one or more local ports to a pod.
proxykubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [flags]Run a proxy to the Kubernetes API server.
replacekubectl replace -f FILENAMEReplace a resource from a file or stdin.
rolling-updatekubectl 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.
runkubectl 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.
scalekubectl scale (-f FILENAME \| TYPE NAME \| TYPE/NAME) --replicas=COUNT [--resource-version=version] [--current-replicas=count] [flags]Update the size of the specified replication controller.
versionkubectl version [--client] [flags]Display the Kubernetes version running on the client and server.

1.2 Resource types

Resource NameShort NamesAPI GroupNamespacedResource Kind
bindingstrueBinding
componentstatusescsfalseComponentStatus
configmapscmtrueConfigMap
endpointseptrueEndpoints
limitrangeslimitstrueLimitRange
namespacesnsfalseNamespace
nodesnofalseNode
persistentvolumeclaimspvctruePersistentVolumeClaim
persistentvolumespvfalsePersistentVolume
podspotruePod
podtemplatestruePodTemplate
replicationcontrollersrctrueReplicationController
resourcequotasquotatrueResourceQuota
secretstrueSecret
serviceaccountssatrueServiceAccount
servicessvctrueService
mutatingwebhookconfigurationsadmissionregistration.k8s.iofalseMutatingWebhookConfiguration
validatingwebhookconfigurationsadmissionregistration.k8s.iofalseValidatingWebhookConfiguration
customresourcedefinitionscrd, crdsapiextensions.k8s.iofalseCustomResourceDefinition
apiservicesapiregistration.k8s.iofalseAPIService
controllerrevisionsappstrueControllerRevision
daemonsetsdsappstrueDaemonSet
deploymentsdeployappstrueDeployment
replicasetsrsappstrueReplicaSet
statefulsetsstsappstrueStatefulSet
tokenreviewsauthentication.k8s.iofalseTokenReview
localsubjectaccessreviewsauthorization.k8s.iotrueLocalSubjectAccessReview
selfsubjectaccessreviewsauthorization.k8s.iofalseSelfSubjectAccessReview
selfsubjectrulesreviewsauthorization.k8s.iofalseSelfSubjectRulesReview
subjectaccessreviewsauthorization.k8s.iofalseSubjectAccessReview
horizontalpodautoscalershpaautoscalingtrueHorizontalPodAutoscaler
cronjobscjbatchtrueCronJob
jobsbatchtrueJob
certificatesigningrequestscsrcertificates.k8s.iofalseCertificateSigningRequest
leasescoordination.k8s.iotrueLease
eventsevevents.k8s.iotrueEvent
ingressesingextensionstrueIngress
networkpoliciesnetpolnetworking.k8s.iotrueNetworkPolicy
poddisruptionbudgetspdbpolicytruePodDisruptionBudget
podsecuritypoliciespsppolicyfalsePodSecurityPolicy
clusterrolebindingsrbac.authorization.k8s.iofalseClusterRoleBinding
clusterrolesrbac.authorization.k8s.iofalseClusterRole
rolebindingsrbac.authorization.k8s.iotrueRoleBinding
rolesrbac.authorization.k8s.iotrueRole
priorityclassespcscheduling.k8s.iofalsePriorityClass
csidriversstorage.k8s.iofalseCSIDriver
csinodesstorage.k8s.iofalseCSINode
storageclassesscstorage.k8s.iofalseStorageClass
volumeattachmentsstorage.k8s.iofalseVolumeAttachment

1.3 Output选项

所有kubectl命令的默认输出格式是人类可读的纯文本格式。 要以特定格式将详细信息输出到终端窗口,可以在支持的kubectl命令中添加-o或–output标志

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

Output formatDescription
-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 jsonOutput 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 namePrint only the resource name and nothing else.
-o wideOutput in the plain-text format with any additional information. For pods, the node name is included.
-o yamlOutput a YAML formatted API object.

示例
在此示例中,以下命令将单个pod的详细信息输出为YAML格式的对象:

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

Custom columns
要定义自定义列并仅将所需的详细信息输出到表中,可以使用custom-columns选项。 您可以选择内联定义自定义列使用模板文件

-o custom-columns=<spec> or -o custom-columns-file=<filename>

内联:

$ kubectl get pods em-tm-em-tm-analysis-1-f7xnj -n zenap  -o custom-columns=NAME:.metadata.name,RSRC:.metadata.resourceVersion
NAME                           RSRC
em-tm-em-tm-analysis-1-f7xnj   529593

Name是列名,.metadata.name 是元信息的name属性,通过:分割
RSRC是列名,.metadata.resourceVersion是元信息的resourceVersion属性,通过:分割

模板文件:
kubectl get pods -o custom-columns-file=template.txt
template.txt内容:

NAME          RSRC
metadata.name metadata.resourceVersion

Server-side columns
kubectl支持从服务器接收有关对象的特定列信息。 这意味着对于任何给定的资源,服务器将返回与该资源相关的列和行,以供客户端打印。 通过让服务器封装打印的详细信息,可以在针对同一群集的客户端之间实现一致的人类可读输出。

默认情况下,在kubectl 1.11及更高版本中启用此功能。 要禁用它,请将–server-print = false标志添加到kubectl get命令

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

输出结果类似

NAME       READY     STATUS              RESTARTS   AGE
pod-name   1/1       Running             0          1m

排序

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

示例:

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

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐