欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

kubectl概述

程序员文章站 2024-03-11 17:03:01
...

官网文档

语法

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服务器的地址和端口。

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

操作命令

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.
api-versions kubectl api-versions [flags] List the API versions that are available.
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).
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.
cluster-info kubectl cluster-info [flags] Display endpoint information about the master and services in the cluster.
config kubectl config SUBCOMMAND [flags] Modifies kubeconfig files. See the individual subcommands for details.
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.
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.
explain kubectl explain [--recursive=false] [flags] Get documentation of various resources. For instance pods, nodes, services, etc.
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.
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.
logs kubectl logs POD [-c CONTAINER] [--follow] [flags] Print the logs for a container in a pod.
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.
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.
proxy kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [flags] Run a proxy to the 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.
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.
version kubectl version [--client] [flags] Display the Kubernetes version running on the client and server.

Resource types

Resource Name Short Names API Group Namespaced Resource Kind
bindings true Binding
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
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

Output选项

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

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.

示例
在此示例中,以下命令将单个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
相关标签: kubectl