k8s学习-kubectl命令常用选项详解与实战
Posted lady_killer9
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了k8s学习-kubectl命令常用选项详解与实战相关的知识,希望对你有一定的参考价值。
目录
概述
语法
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 k8s kubectl常用命令总结