概述
语法
kubectl [command] [TYPE] [NAME] [flags]
- command: 指定要对资源执行的操作,例如,create、get、describe和delete
- type: 指定资源类型,资源类型不区分大小写, 可以指定单数、复数或缩写形式。
- name:指定资源的名称,名称区分大小写。 如果省略名称,则显示所有资源的详细信息。
- flags:指定可选的参数。例如,可用-s 或者–server 参数指定 Kubernetes API server 的地址和端口。
-h查看所有命令
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 or Replication Controller 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).
之后实战的分类,就大致按照帮助命令的分类进行展示了。
再看下选项
The following options can be passed to any command: --add-dir-header=false: If true, adds the file directory to the header --alsologtostderr=false: log to standard error as well as files --as='': Username to impersonate for the operation --as-group=[]: Group to impersonate for the operation, this flag can be repeated to specify multiple groups. --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 --cluster='': The name of the kubeconfig cluster to use --context='': The name of the kubeconfig context to use --insecure-skip-tls-verify=false: If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure --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-dir='': If non-empty, write log files in this directory --log-file='': If non-empty, use this log file --log-file-max-size=1800: Defines the maximum size a log file can grow to. Unit is megabytes. If the value is 0, the maximum file size is unlimited. --log-flush-frequency=5s: Maximum number of seconds between log flushes --logtostderr=true: log to standard error instead of files --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 --profile='none': Name of profile to capture. One of (none|cpu|heap|goroutine|threadcreate|block|mutex) --profile-output='profile.pprof': Name of the file to write the profile to --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 --skip-headers=false: If true, avoid header prefixes in the log messages --skip-log-headers=false: If true, avoid headers when opening log files --stderrthreshold=2: logs at or above this threshold go to stderr --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: number for the log level verbosity --vmodule=: comma-separated list of pattern=N settings for file-filtered logging
经常用的是–cluster指定集群,-n指定命名空间
资源类型
kubectl api-resources
资源名 | 缩写名 | API 分组 | 按命名空间 | 资源类型 |
bindings |
true | Binding | ||
componentstatuses |
cs |
false | ComponentStatus | |
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 |
资源名的缩写大家还是要记一下,之后的文章敲命令我也会多用缩写。常用的有:
- cm:ConfigMap
- ns:NameSpace
- no:Node
- pvc:PersistentVolumeClaim
- pv:PersistentVolume
- po:Pod
- rc:ReplicationController
- sa:ServiceAccount
- svc:Service
- ds:DaemonSet
- deploy:Deployment
- rs:ReplicaSet
- sts:StatefulSet
- cj:CronJob
输出选项
kubectl [command] [TYPE] [NAME] -o=<output_format>
Output format | Description |
-o custom-columns=<spec> |
使用逗号分隔的自定义列列表打印表。 |
-o custom-columns-file=<filename> |
使用 <filename> 文件中的自定义列模板打印表。 |
-o json |
输出 JSON 格式的 API 对象 |
-o jsonpath=<template> |
打印 jsonpath 表达式定义的字段 |
-o jsonpath-file=<filename> |
打印 <filename> 文件中 jsonpath 表达式定义的字段。 |
-o name |
仅打印资源名称而不打印任何其他内容。 |
-o wide |
以纯文本格式输出,包含任何附加信息。对于 pod 包含节点名。 |
-o yaml |
输出 YAML 格式的 API 对象。 |
常用 -o yaml,一般使用yaml文件,看的比json清晰,配置项太多了json的花括号看着很乱。
实战
基本命令
create
从命令行或文件创建资源,可以是json或yaml格式。命令格式如下:
kubectl create -f FILENAME [options]
选项如下:
Options: --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. --dry-run=false: If true, only print the object that would be sent, without sending it. --edit=false: Edit the API resource before creating -f, --filename=[]: Filename, directory, or URL to files to use to create the resource -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R. -o, --output='': Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file. --raw='': Raw URI to POST to the server. Uses the transport specified by the kubeconfig file. --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2) --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]. --validate=true: If true, use a schema to validate the input before sending it --windows-line-endings=false: Only relevant if --edit=true. Defaults to the line ending native to your platform.
常用选项:
- –dry-run:不执行命令,打印资源文件
创建命名空间 lady-killer9
kubectl create ns lady-killer9
在命名空间lady-killer9中创建pod nginx-test
kubectl create -f nginx-test.yaml
nginx-test.yaml文件
apiVersion: v1 kind: Pod metadata: name: nginx-test labels: app: nginx role: backend spec: containers: - name: nginx image: nginx ports: - name: http containerPort: 80
get
展示一个或多个资源,可以通过label或selector进行过滤,命令格式如下:
kubectl get [(-o|--output=)json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...] (TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags] [options]
选项如下:
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|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://kubernetes.io/docs/user-guide/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) --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) --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. --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. Uninitialized objects are excluded if no object name is provided. --watch-only=false: Watch for changes to the requested object(s), without listing/getting first.
常用选项:
- -A:查看所有
- –include-uninitialized:未初始化的也显示
- -o wide:查看详细信息
导出yaml文件
kubectl get ns lady-killer9 -o yaml > lady-killer9.yaml
查看yaml文件
cat lady-killer9.yaml apiVersion: v1 kind: Namespace metadata: creationTimestamp: "2022-05-03T09:58:15Z" name: lady-killer9 resourceVersion: "80501" selfLink: /api/v1/namespaces/lady-killer9 uid: bfdf94d9-a5b9-429d-8078-3e173c186973 spec: finalizers: - kubernetes status: phase: Active
查看pod
kubectl get po -n lady-killer9
查看多个资源,逗号分隔即可
kubectl get po,ns
查看资源的更多信息
kubectl get po -n lady-killer9 -o wide
可以看到ip等信息
edit
使用默认编辑器编辑资源,默认是yaml
kubectl edit (RESOURCE/NAME | -f FILENAME) [options]
Options: --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. -f, --filename=[]: Filename, directory, or URL to files to use to edit the resource -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R. -o, --output='': Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file. --output-patch=false: Output the patch if the resource is edited. --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object 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]. --validate=true: If true, use a schema to validate the input before sending it --windows-line-endings=false: Defaults to the line ending native to your platform.
命令
kubectl edit ns lady-killer9
结果
可以看到,在tmp目录下有该文件。这里就不做改变了,个人使用replace多一点。
delete
通过文件、资源名、标签等删除资源,命令格式如下:
kubectl delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label | --all)]) [options]
选项如下:
Options: --all=false: Delete all resources, including uninitialized ones, in the namespace of the specified resource types. -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. --cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true. --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=[]: containing the resource to delete. --force=false: Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation. --grace-period=-1: Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion). --ignore-not-found=false: Treat "resource not found" as a successful delete. Defaults to "true" when --all is specified. -k, --kustomize='': Process a kustomization directory. This flag can't be used together with -f or -R. --now=false: If true, resources are signaled for immediate shutdown (same as --grace-period=1). -o, --output='': Output mode. Use "-o name" for shorter output (resource/name). --raw='': Raw URI to DELETE to 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, not including uninitialized ones. --timeout=0s: The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object --wait=true: If true, wait for resources to be gone before returning. This waits for finalizers.
常用选项:
- – all:删除所有资源,包括未初始化的
- –now:立刻删除,与–grace-period=1一样
- –force:立即删除,跳过 grace period,此时设置–grace-period=0
- –grace-period:优雅删除时间,单位s。
- -l :标签过滤
因为资源通常代表集群中的实体,所以可能不能够立即删除。例如,删除pod时,确保你的pod已经停止,或强制删除对应用没有影响。
这是default命名空间的,不是上面自己创建的pod,没有彻底删除,是因为使用的deployment。
集群管理
cluster-info
查看集群信息
kubectl cluster-info
top
查看pod或node的资源占用情况
kubectl top pod/node
cordon && uncordon
节点是否可以调度,命令格式:
kubectl cordon/uncordon NODE [options]
选项如下:
Options: --dry-run=false: If true, only print the object that would be sent, without sending it. -l, --selector='': Selector (label query) to filter on
在资源调度的文章中再展示
drain
驱逐节点,为维护做好准备。
节点将标记为不可调度,使用uncordon使节点可以调度,命令格式:
kubectl drain NODE [options]
选项如下:
Options: --delete-local-data=false: Continue even if there are pods using emptyDir (local data that will be deleted when the node is drained). --dry-run=false: If true, only print the object that would be sent, without sending it. --force=false: Continue even if there are pods not managed by a ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet. --grace-period=-1: Period of time in seconds given to each pod to terminate gracefully. If negative, the default value specified in the pod will be used. --ignore-daemonsets=false: Ignore DaemonSet-managed pods. --pod-selector='': Label selector to filter pods on the node -l, --selector='': Selector (label query) to filter on --timeout=0s: The length of time to wait before giving up, zero means infinite
- –ignore-daemonsets:有守护进程的POD也会删除
- –force:继续即使有不被 RC RS Job DS STS管理的Pod
例如
kubectl drain foo --force
taint
更新节点上的污点。
- 污点由 key, value 和effect组成,例如,key=value:effect。
- key必须以字母或数字开头,可以包含字母、数字、连字符、点和下划线,最多253个字符。
- value是可选的,如果给定,必须以字母或数字开头,可以包含字母、数字、连字符、点和下划线,最多63个字符。
- effect必须是NoSchedule、PreferNoSchedule或NoExecute。
命令格式如下:
kubectl taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ... KEY_N=VAL_N:TAINT_EFFECT_N [options]
选项如下:
Options: --all=false: Select all nodes in the cluster --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. -o, --output='': Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file. --overwrite=false: If true, allow taints to be overwritten, otherwise reject taint updates that overwrite existing taints. -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2) --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]. --validate=true: If true, use a schema to validate the input before sending it
- –all:全部节点
- –overwrite:如果为true,则允许覆盖污点,否则拒绝覆盖现有的污点。
- -l:筛选
添加污点
kubectl taint nodes foo dedicated=special-user:NoSchedule
移除污点
kubectl taint nodes foo dedicated:NoSchedule-
根据label添加污点
kubectl taint node -l myLabel=X dedicated=foo:PreferNoSchedule
在资源调度的文章中再展示
高级命令
apply
将配置应用于某资源,若资源还不存在就创建。和create --save-config差不多。命令格式如下:
kubectl apply (-f FILENAME | -k DIRECTORY) [options]
选项如下:
Options: --all=false: Select all resources in the namespace of the specified resource types. --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. --cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true. --dry-run=false: If true, only print the object that would be sent, without sending it. Warning: --dry-run cannot accurately output the result of merging the local manifest and the server-side data. Use --server-dry-run to get the merged result instead. --field-manager='kubectl': Name of the manager used to track field ownership. -f, --filename=[]: that contains the configuration to apply --force=false: Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation. --force-conflicts=false: If true, server-side apply will force the changes against conflicts. --grace-period=-1: Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion). -k, --kustomize='': Process a kustomization directory. This flag can't be used together with -f or -R. --openapi-patch=true: If true, use openapi to calculate diff when the openapi presents and the resource can be found in the openapi spec. Otherwise, fall back to use baked-in types. -o, --output='': Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file. --overwrite=true: Automatically resolve conflicts between the modified and live configuration by using values from the modified configuration --prune=false: Automatically delete resource objects, including the uninitialized ones, that do not appear in the configs and are created by either apply or create --save-config. Should be used with either -l or --all. --prune-whitelist=[]: Overwrite the default whitelist with <group/version/kind> for --prune --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. -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) --server-dry-run=false: If true, request will be sent to server with dry-run flag, which means the modifications won't be persisted. This is an alpha feature and flag. --server-side=false: If true, apply runs in the server instead of the client. --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]. --timeout=0s: The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object --validate=true: If true, use a schema to validate the input before sending it --wait=false: If true, wait for resources to be gone before returning. This waits for finalizers.
例子,
nginx-test-apply.yaml
apiVersion: v1 kind: Pod metadata: name: nginx-test-apply labels: app: nginx role: backend spec: containers: - name: nginx image: nginx ports: - name: http containerPort: 80
命令
kubectl apply -f nginx-test-apply.yaml -n lady-killer9
结果
相对于create,文件没有改动时不会报错。
replace
替换资源,命令格式如下:
kubectl replace -f FILENAME [options]
选项如下:
Options: --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. --cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true. -f, --filename=[]: to use to replace the resource. --force=false: Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation. --grace-period=-1: Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion). -k, --kustomize='': Process a kustomization directory. This flag can't be used together with -f or -R. -o, --output='': Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file. --raw='': Raw URI to PUT to 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. --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object 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]. --timeout=0s: The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object --validate=true: If true, use a schema to validate the input before sending it --wait=false: If true, wait for resources to be gone before returning. This waits for finalizers.
只能替换部分字段,尝试修改spec.containers的ports字段
apiVersion: v1 kind: Pod metadata: name: nginx-test-apply labels: app: nginx role: backend spec: containers: - name: nginx image: nginx ports: - name: http containerPort: 80 - name: https containerPort: 443
命令
kubectl replace -f nginx-test-apply.yaml -n lady-killer9ls
结果
pod更新不能更改spec.containers[*].image
, spec.initContainers[*].image
, spec.activeDeadlineSeconds
或者spec.tolerations
(仅添加到现有的toleration中)以外的字段
故障诊断和调试
describe
显示指定资源或资源组的详细信息,命令格式如下:
kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME) [options]
选项如下:
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. -f, --filename=[]: Filename, directory, or URL to files containing the resource to describe -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R. -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) --show-events=true: If true, display events related to the described object.
例子,
命令
kubectl describe po/nginx-test-apply -n lady-killer9
结果
logs
打印pod或指定资源中容器的日志。如果pod只有一个容器,则容器名称是可选的。命令格式如下:
kubectl logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER] [options]
选项如下:
Options: --all-containers=false: Get all containers' logs in the pod(s). -c, --container='': Print the logs of this container -f, --follow=false: Specify if the logs should be streamed. --ignore-errors=false: If watching / following pod logs, allow for any errors that occur to be non-fatal --insecure-skip-tls-verify-backend=false: Skip verifying the identity of the kubelet that logs are requested from. In theory, an attacker could provide invalid log content back. You might want to use this if your kubelet serving certificates have expired. --limit-bytes=0: Maximum bytes of logs to return. Defaults to no limit. --max-log-requests=5: Specify maximum number of concurrent logs to follow when using by a selector. Defaults to 5. --pod-running-timeout=20s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running --prefix=false: Prefix each log line with the log source (pod name and container name) -p, --previous=false: If true, print the logs for the previous instance of the container in a pod if it exists. -l, --selector='': Selector (label query) to filter on. --since=0s: Only return logs newer than a relative duration like 5s, 2m, or 3h. Defaults to all logs. Only one of since-time / since may be used. --since-time='': Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time / since may be used. --tail=-1: Lines of recent log file to display. Defaults to -1 with no selector, showing all log lines otherwise 10, if a selector is provided. --timestamps=false: Include timestamps on each line in the log output
- –all-containers:pod中所有容器的日志
- -p:如果为true,则打印pod中容器的前一个实例(如果存在)的日志。
- -c:指定容器
- –tail:看最近的日志
- –since: 看最近多久时间的日志
例子:
查看pod nginx-test-apply日志
kubectl logs po/nginx-test-apply -n lady-killer9
查看pod nginx-test-apply中 nginx容器的日志
kubectl logs po/nginx-test-apply -c nginx -n lady-killer9
结果同上
查看pod nginx-test-apply后10行日志
kubectl logs --tail=10 po/nginx-test-apply
查看pod nginx-test-apply近一个小时的日志
kubectl logs --since=1h po/nginx-test-apply -n lady-killer9
exec
在容器中执行命令。未指定pod中的容器时默认为第一个。命令格式如下:
kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...] [options]
选项如下:
Options: -c, --container='': Container name. If omitted, the first container in the pod will be chosen --pod-running-timeout=1m0s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running -i, --stdin=false: Pass stdin to the container -t, --tty=false: Stdin is a TTY
例子,
在pod nginx-test-apply的第一个容器中指定date命令
kubectl exec nginx-test-apply -n lady-killer9 date
结果
把输入定向到容器中,结果返回出来,形成类似反弹shell的交互式命令
kubectl exec nginx-test-apply -n lady-killer9 -i -t -- bash -il
执行的命令有参数,使用 –
kubectl exec nginx-test-apply -n lady-killer9 -i -t -- ls -t /usr/local/
结果
设置命令
label
添加、更新、删除资源上的标签。
- 标签的key和value必须以字母或数字开头,可以包含字母、数字、连字符、点和数字
下划线,每个下划线最多63个字符。 - 如果–overwrite为true,则可以覆盖现有标签,否则尝试覆盖标签将失败导致错误。
- 如果指定了–resource version,则更新将使用此资源版本,否则现有的将使用资源版本。
命令格式如下:
kubectl label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version][options]
选项如下:
Options: --all=false: Select all resources, including uninitialized ones, in the namespace of the specified resource types --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. --dry-run=false: If true, only print the object that would be sent, without sending it. --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 update the labels -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R. --list=false: If true, display the labels for a given resource. --local=false: If true, label will NOT contact api-server but run locally. -o, --output='': Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file. --overwrite=false: If true, allow labels to be overwritten, otherwise reject label updates that overwrite existing labels. --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. --resource-version='': If non-empty, the labels update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource. -l, --selector='': Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). --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].
添加
kubectl label node k8s-node01 unhealthy=true
查看
kubectl get node --show-labels
更新
kubectl label --overwrite node k8s-node01 unhealthy=false
删除
kubectl label node k8s-node01 unhealthy-
其他命令
version
kubectl version