kubectl 命令

痴心易碎 提交于 2021-02-13 09:49:05

https://jimmysong.io/kubernetes-handbook/guide/using-kubectl.html
零、Options 选项
https://www.kubernetes.org.cn/doc-45
功能: 使用kubectl来管理Kubernetes集群。
可以在 https://github.com/kubernetes/kubernetes 找到更多的信息。
选项:
--kubeconfig="": 命令行请求使用的配置文件路径。
--api-version="": 和服务端交互使用的API版本。
--certificate-authority="": 用以进行认证授权的.cert文件路径。
--client-certificate="": TLS使用的客户端证书路径。
--client-key="": TLS使用的客户端密钥路径。
--cluster="": 指定使用的kubeconfig配置文件中的集群名。
--context="": 指定使用的kubeconfig配置文件中的环境名。
--user="": 指定使用的kubeconfig配置文件中的用户名。
--insecure-skip-tls-verify[=false]: 如果为true,将不会检查服务器凭证的有效性,这会导致你的HTTPS链接变得不安全。
--match-server-version[=false]: 要求服务端和客户端版本匹配。
--namespace="": 如果不为空,命令将使用此namespace。
--token="": 认证到API Server使用的令牌。
-s, --server="": Kubernetes API Server的地址和端口号。
--username="": API Server进行简单认证使用的用户名。
--password="": API Server进行简单认证使用的密码。
--log-dir="": 如果不为空,将日志文件写入此目录。
--log-flush-frequency=5s: 刷新日志的最大时间间隔。
--v=0: 指定输出日志的级别。
--vmodule=: 指定输出日志的模块,格式如下:pattern=N,使用逗号分隔。
--log-backtrace-at=:0: 当日志长度超过定义的行数时,忽略堆栈信息。
--stderrthreshold=2: 高于此级别的日志将被输出到错误控制台。
--logtostderr[=true]: 输出日志到标准错误控制台,不输出到文件。
--alsologtostderr[=false]: 同时输出日志到标准错误控制台和文件。

一、Basic Commands (Beginner)基本命令(初学者)
1.kubectl create命令
http://docs.kubernetes.org.cn/490.html
功能:通过配置文件名或stdin创建一个集群资源对象。支持JSON和YAML格式的文件。
语法:kubectl create -f object.yaml/json
资源对象类型包括:
configmap
namespace
deployment
quota
secrete
service
serviceaccount
示例:
通过pod.json文件创建一个pod。
kubectl create -f ./pod.json
通过stdin的JSON创建一个pod。
cat pod.json | kubectl create -f -
API版本为v1的JSON格式的docker-registry.yaml文件创建资源。
kubectl create -f docker-registry.yaml --edit --output-version=v1 -o json
选项说明:

2.kubectl expose命令
http://docs.kubernetes.org.cn/475.html
功能:将资源暴露为新的Kubernetes Service
资源包括(不区分大小写):pod(po),service(svc),replication controller(rc),deployment(deploy),replica set(rs)
语法:
$ expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]
选项说明:

3.kubectl run命令
http://docs.kubernetes.org.cn/468.html
功能:创建并运行一个或多个容器镜像;创建一个deployment 或job 来管理容器。
语法:
$ run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [--command] -- [COMMAND] [args...]
示例:
启动nginx实例。
kubectl run nginx --image=nginx
启动hazelcast实例,暴露容器端口 5701。
kubectl run hazelcast --image=hazelcast --port=5701
启动hazelcast实例,在容器中设置环境变量“DNS_DOMAIN = cluster”和“POD_NAMESPACE = default”。
kubectl run hazelcast --image=hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default"
启动nginx实例,设置副本数5。
kubectl run nginx --image=nginx --replicas=5
运行 Dry 打印相应的API对象而不创建它们。
kubectl run nginx --image=nginx --dry-run
选项说明:

4.kubectl set命令
http://docs.kubernetes.org.cn/669.html
功能:配置应用资源,使用这些命令能帮你更改现有应用资源一些信息。
语法:
$ set SUBCOMMAND
子命令:
4.1 image
http://docs.kubernetes.org.cn/670.html
功能:更新现有的资源对象的容器镜像。
可使用资源对象包括(不区分大小写):
pod (po)、replicationcontroller (rc)、deployment (deploy)、daemonset (ds)、job、replicaset (rs)
语法:
$ image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N
示例
将deployment中的nginx容器镜像设置为“nginx:1.9.1”。
kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1
所有deployment和rc的nginx容器镜像更新为“nginx:1.9.1”
kubectl set image deployments,rc nginx=nginx:1.9.1 --all
将daemonset abc的所有容器镜像更新为“nginx:1.9.1”
kubectl set image daemonset abc *=nginx:1.9.1
从本地文件中更新nginx容器镜像
kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml
选项说明:

4.2 resources
http://docs.kubernetes.org.cn/671.html
功能:资源对象中的Pod可以指定计算资源需求(CPU-单位m、内存-单位Mi),即使用的最小资源请求(Requests),限制(Limits)的最大资源需求,Pod将保证使用在设置的资源数量范围。
Requests:计算资源最小数量。
Limits:资源最大允许数量。
对于每个Pod资源,如果指定了Limits(限制)值,并省略了Requests(请求),则Requests默认为Limits的值。
可用资源对象包括(支持大小写):replicationcontroller、deployment、daemonset、job、replicaset。
语法:
$ resources (-f FILENAME | TYPE NAME) ([--limits=LIMITS & --requests=REQUESTS]
示例:
将deployment的nginx容器cpu限制为“200m”,将内存设置为“512Mi”
kubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi
为nginx中的所有容器设置 Requests和Limits
kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi
删除nginx中容器的计算资源值
kubectl set resources deployment nginx --limits=cpu=0,memory=0 --requests=cpu=0,memory=0
打印从本地更新nginx容器限制的结果(以yaml格式),而不会触发服务器。打印结果(以yaml格式),在不影响服务器的情况下,从本地更新nginx容器限制
kubectl set resources -f path/to/file.yaml --limits=cpu=200m,memory=512Mi --local -o yaml

4.3 selector
http://docs.kubernetes.org.cn/672.html
功能:设置资源的selector(选择器)。
如果在调用"set selector"命令之前已经存在选择器,则新创建的选择器将覆盖原来的选择器。
selector必须以字母或数字开头,最多包含63个字符,可使用:字母、数字、连字符" - " 、点"."和下划线" _ "。
如果指定了--resource-version,则更新将使用此资源版本,否则将使用现有的资源版本。
注意:目前selector命令只能用于Service对象。
语法:
$ selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resource-version=version]
示例
在创建deployment/service对之前设置labels和selector。
kubectl create service clusterip my-svc --clusterip="None" -o yaml --dry-run | kubectl set selector --local -f - 'environment=qa' -o yaml | kubectl create -f -
kubectl create deployment my-dep -o yaml --dry-run | kubectl label --local -f - environment=qa -o yaml | kubectl create -f -

4.4 subject
http://docs.kubernetes.org.cn/681.html
功能:更新RoleBinding / ClusterRoleBinding中User、Group 或 ServiceAccount。
语法:subject (-f FILENAME | TYPE NAME) [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run]
示例:
更新一个ClusterRoleBinding 的 serviceaccount1
kubectl set subject clusterrolebinding admin --serviceaccount=namespace:serviceaccount1
更新RoleBinding的user1,user2和group1
kubectl set subject rolebinding admin --user=user1 --user=user2 --group=group1

二、Basic Commands (Intermediate)基本命令(中间)
1.kubectl get命令
http://docs.kubernetes.org.cn/626.html
功能:获取列出一个或多个资源的信息。
可以使用的资源包括:
all
certificatesigningrequests (aka 'csr')
clusterrolebindings
clusterroles
clusters (valid only for federation apiservers)
componentstatuses (aka 'cs')
configmaps (aka 'cm')
controllerrevisions
cronjobs
daemonsets (aka 'ds')
deployments (aka 'deploy')
endpoints (aka 'ep')
events (aka 'ev')
horizontalpodautoscalers (aka 'hpa')
ingresses (aka 'ing')
jobs
limitranges (aka 'limits')
namespaces (aka 'ns')
networkpolicies (aka 'netpol')
nodes (aka 'no')
persistentvolumeclaims (aka 'pvc')
persistentvolumes (aka 'pv')
poddisruptionbudgets (aka 'pdb')
podpreset
pods (aka 'po')
podsecuritypolicies (aka 'psp')
podtemplates
replicasets (aka 'rs')
replicationcontrollers (aka 'rc')
resourcequotas (aka 'quota')
rolebindings
roles
secrets
serviceaccounts (aka 'sa')
services (aka 'svc')
statefulsets
storageclasses
thirdpartyresources

语法:
$ get [(-o|--output=)json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...] (TYPE [NAME | -l label] | TYPE/NAME ...) [flags]
kubectl get 资源类型
资源类型包括:
pods(po)
replicationcontrollers(rc) 副本控制
replicasets(rs) 副本集
deployments(deploy) 部署
statefulsets 有状态的集合
daemonsets(ds) 守护进程集合
jobs 定时器
horizontalpodautoscalers(hpa) Pod水平自动扩展

nodes(no) 节点
namespaces(ns) 命名空间
services(svc) 服务
secrets 机密
configmaps(cm) 配置映射
ingresses(ing) 入口
thirdpartyresources 第三方资源
serviceaccounts(sa) 服务账户

persistentvolumes(pv) 持久卷
persistentvolumeclaims(pvc) 持久卷声明
storadeclasses 存储类

resourcequotas(quota) 资源配额
limitranges(limits) 限制范围

podtemplates Pod模板
podsecuritypolicies(psp) Pod安全策略
componentstatuses(cs) 组件状态
networkpolicies 网络策略
clusters 集群
events(ev) 事件
endpoints(ep) 终端
示例:
exp1: 列出所有运行的Pod信息。
kubectl get pods
exp2: 列出Pod以及运行Pod节点信息。
kubectl get pods -o wide
exp3: 列出指定NAME的 replication controller信息。
kubectl get replicationcontroller web
exp4: 以JSON格式输出一个pod信息。
kubectl get -o json pod web-pod-13je7
exp5: 以“pod.yaml”配置文件中指定资源对象和名称输出JSON格式的Pod信息。
kubectl get -f pod.yaml -o json
exp6: 返回指定pod的相位值。
kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}
exp7: 列出所有replication controllers和service信息。
kubectl get rc,services
exp8: 按其资源和名称列出相应信息。
kubectl get rc/web service/frontend pods/web-pod-13je7
exp9: 列出所有不同的资源对象。
kubectl get all
选项说明:
--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.
--experimental-use-openapi-print-columns:false If true, use x-kubernetes-print-column metadata (if present) from openapi schema for displaying a resource.
--export:false If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information.
--filename/-f:[] Filename, directory, or URL to files identifying the resource to get from a server.
--ignore-not-found:false Treat "resource not found" as a successful retrieval.
--include-extended-apis:true If true, include definitions of new APIs via calls to the API server. [default true]
--label-columns/-L:[] 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).
--output/-o 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-version DEPRECATED: To use a specific API version, fully-qualify the resource, version, and group (for example: 'jobs.v1.batch/myjob').
--raw Raw URI to request from the server. Uses the transport specified by the kubeconfig file.
--recursive/-R:false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
--schema-cache-dir:~/.kube/schema If non-empty, load/store cached API schemas in this directory, default is '$HOME/.kube/schema'
--selector/-l Selector (label query) to filter on, supports '=', '==', and '!='.
--show-all/-a:false When printing, show all resources (default hide terminated pods.)
--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].
--watch/-w:false After listing/getting the requested object, watch for changes.
--watch-only:false Watch for changes to the requested object(s), without listing/getting first.

2.kubectl explain命令
功能:资源文档
语法:
示例:

3.kubectl edit命令
https://www.kubernetes.org.cn/doc-62
功能:编辑服务端的资源。
使用系统默认编辑器编辑服务端的资源。
edit命令允许你直接编辑使用命令行工具获取的任何资源。
此命令将打开你通过KUBE_EDITOR,GIT_EDITOR 或者EDITOR环境变量定义的编辑器,或者直接使用“vi”。
你可以同时编辑多个资源,但所有的变更都只会一次性提交。
除了命令行参数外,此命令也接受文件名,但所直指定的文件必须使用早于当前的资源版本。
所编辑的文件将使用默认的API版本输出,或者通过–output-version选项显式指定。
默认的输出格式是YAML, 如果你需要使用JSON格式编辑,使用-o json选项。
如果当更新资源的时候出现错误,将会在磁盘上创建一个临时文件,记录未成功的更新。
更新资源时最常见的错误是其他人也在更新服务端的资源。
当这种情况发生时,你需要将你所作的更改应用到最新版本的资源上,或者编辑保存的临时文件,使用最新的资源版本。
语法:kubectl edit (RESOURCE/NAME | -f FILENAME)
示例:
exp1: 编辑名为“docker-registry”的service
$ kubectl edit svc/docker-registry
exp2: 使用一个不同的编辑器
$ KUBE_EDITOR="nano" kubectl edit svc/docker-registry
exp3: 编辑名为“docker-registry”的service,使用JSON格式、v1 API版本
$ kubectl edit svc/docker-registry --output-version=v1 -o json
选项说明:
-f, --filename=[]: 用来指定待编辑资源的文件名,目录名或者URL。
-o, --output="yaml": 输出格式,可选yaml或者json中的一种。
--output-version="": 输出资源使用的API版本(默认使用api-version)。

4.kubectl delete命令
http://docs.kubernetes.org.cn/618.html
功能:
通过配置文件名、stdin、资源名称或label选择器来删除资源。
支持JSON和YAML格式文件。可以只指定一种类型的参数:文件名、资源名称或label选择器。
有些资源,如pod,支持优雅的(graceful)删除,因为这些资源一般是集群中的实体,所以删除不可能会立即生效,这些资源在强制终止之前默认定义了一个周期(宽限期),但是你可以使用--grace-period flag来覆盖该值,或者通过pass --now设置该周期为1。
如果托管Pod的Node节点已经停止或者无法连接API Server,使用delete命令删除Pod需等待时间更长。要强制删除资源,需指定- force flag,且设置周期(宽限期)为0。
如果执行强制删除Pod,则调度程序会在节点释放这些Pod之前将新的Pod放在这些节点上,并使之前Pod立即被逐出。
注意:执行delete命令时不会检查资源版本,如果在执行delete操作时有人进行了更新操作,那么更新操作将连同资源一起被删除。
语法:
$ delete ([-f FILENAME] | TYPE [(NAME | -l label | --all)])
示例:
exp1: 使用 pod.json中指定的资源类型和名称删除pod。
kubectl delete -f ./pod.json
exp2: 根据传入stdin的JSON所指定的类型和名称删除pod。
cat pod.json | kubectl delete -f -
exp3: 删除名为“baz”和“foo”的Pod和Service。
kubectl delete pod,service baz foo
exp4: 删除 Label name = myLabel的pod和Service。
kubectl delete pods,services -l name=myLabel
exp5: 强制删除dead node上的pod
kubectl delete pod foo --grace-period=0 --force
exp6: 删除所有pod
kubectl delete pods --all
选项说明:

三、Deploy Commands 部署命令
1.kubectl rollout命令
http://docs.kubernetes.org.cn/643.html
功能:对资源进行管理
可用资源包括:deployments、daemonsets
语法:
$ rollout SUBCOMMAND
子命令:
1.1 history(查看历史版本)
http://docs.kubernetes.org.cn/645.html
功能:查看之前推出的版本(历史版本)。
语法:
kubectl rollout history (TYPE NAME | TYPE/NAME) [flags]
示例:
exp1: 查看deployment的历史记录
kubectl rollout history deployment/abc
exp2: 查看daemonset修订版3的详细信息
kubectl rollout history daemonset/abc --revision=3
选项说明:
--filename/-f=[] Filename, directory, or URL to files identifying the resource to get from a server.
--recursive/-R=false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
--revision=0 See the details, including podTemplate of the revision specified

1.2 pause(暂停资源)
http://docs.kubernetes.org.cn/647.html
功能:
将提供的资源标记为暂停
被pause命令暂停的资源不会被控制器协调使用,可以是“kubectl rollout resume”命令恢复已暂停资源。
目前仅支持的资源:deployments。
语法:
kubectl rollout pause RESOURCE
示例:
将deployment标记为暂停。#只要deployment在暂停中,使用deployment更新将不会生效。
kubectl rollout pause deployment/nginx
选项说明:
--filename/-f=[] Filename, directory, or URL to files identifying the resource to get from a server.
--recursive/-R=false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.

1.3 resume(恢复暂停资源)
http://docs.kubernetes.org.cn/650.html
功能:恢复已暂停的资源
被pause命令暂停的资源将不会被控制器协调使用。可以通过resume来恢复资源。目前仅支持恢复deployment资源。
语法:
kubectl rollout resume RESOURCE
示例:
恢复已暂停的 deployment
kubectl rollout resume deployment/nginx
选项说明:
--filename/-f=[] Filename, directory, or URL to files identifying the resource to get from a server.
--recursive/-R=false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.

1.4 status(查看资源状态)
http://docs.kubernetes.org.cn/652.html
功能:查看资源的状态。
使用--watch = false 来查看当前状态,需要查看特定修订版本状态 请使用--revision = N 来指定。
语法:$ status (TYPE NAME | TYPE/NAME) [flags]
示例:查看deployment的状态
kubectl rollout status deployment/nginx
选项说明:
--filename/-f=[] Filename, directory, or URL to files identifying the resource to get from a server.
--recursive/-R=false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
--revision=0 See the details, including podTemplate of the revision specified
--watch/-w=true Watch the status of the rollout until it's done.

1.5 undo(回滚版本)
http://docs.kubernetes.org.cn/654.html
功能:回滚到之前的版本。
语法:$ undo (TYPE NAME | TYPE/NAME) [flags]
示例:
exp1: 回滚到之前的deployment
kubectl rollout undo deployment/abc
kubectl rollout undo --dry-run=true deployment/abc
回滚到daemonset 修订3版本
kubectl rollout undo daemonset/abc --to-revision=3
选项说明:
--dry-run=false If true, only print the object that would be sent, without sending it.
--filename/-f=[] Filename, directory, or URL to files identifying the resource to get from a server.
--recursive/-R=false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
--to-revision=0 The revision to rollback to. Default to 0 (last revision).

2.kubectl rolling-update命令
http://docs.kubernetes.org.cn/638.html
功能:执行指定ReplicationController的滚动更新。
该命令创建了一个新的RC, 然后一次更新一个pod方式逐步使用新的PodTemplate,最终实现Pod滚动更新,new-controller.json需要与之前RC在相同的namespace下。
语法:$ rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE | -f NEW_CONTROLLER_SPEC)
示例:
exp1: 使用frontend-v2.json中的新RC数据更新frontend-v1的pod。
kubectl rolling-update frontend-v1 -f frontend-v2.json
exp2: 使用JSON数据更新frontend-v1的pod。
cat frontend-v2.json | kubectl rolling-update frontend-v1 -f -
exp3:
kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2
kubectl rolling-update frontend --image=image:v2
kubectl rolling-update frontend-v1 frontend-v2 --rollback
选项说明:

3.kubectl scale命令
http://docs.kubernetes.org.cn/664.html
功能:扩容或缩容 Deployment、ReplicaSet、Replication Controller或 Job 中Pod数量。
scale也可以指定多个前提条件,如:当前副本数量或 --resource-version ,进行伸缩比例设置前,系统会先验证前提条件是否成立。
语法:$ scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)
示例:
exp1: 将名为foo中的pod副本数设置为3。
kubectl scale --replicas=3 rs/foo
exp2: 将由“foo.yaml”配置文件中指定的资源对象和名称标识的Pod资源副本设为3。
kubectl scale --replicas=3 -f foo.yaml
exp3: 如果当前副本数为2,则将其扩展至3。
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
exp4: 设置多个RC中Pod副本数量。
kubectl scale --replicas=5 rc/foo rc/bar rc/baz
选项说明:

4.kubectl autoscale命令
http://docs.kubernetes.org.cn/486.html
功能:使用 autoscaler 自动设置在kubernetes集群中运行的pod数量(水平自动伸缩)。
指定Deployment、ReplicaSet或ReplicationController,并创建已经定义好资源的自动伸缩器。
使用自动伸缩器可以根据需要自动增加或减少系统中部署的pod数量。
语法:$ autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]
示例:
exp1: 使用 Deployment “foo”设定,使用默认的自动伸缩策略,指定目标CPU使用率,使其Pod数量在2到10之间。
kubectl autoscale deployment foo --min=2 --max=10
exp2: 使用RC“foo”设定,使其Pod的数量介于1和5之间,CPU使用率维持在80%。
kubectl autoscale rc foo --max=5 --cpu-percent=80
选项说明:

四、Cluster Management Commands集群管理命令
1.kubectl certificate命令
功能:修改证书资源。

2.kubectl cluster-info命令
https://www.kubernetes.org.cn/doc-50
功能:显示集群信息。
语法:kubectl cluster-info

3.kubectl top命令
功能:展示资源 (CPU/Memory/Storage) 使用信息。
语法:kubectl top node|pod
4.kubectl cordon命令
功能:将 node 节点标记为不可调度

5.kubectl uncordon命令
功能:标记 node 节点为可调度

6.kubectl drain命令
功能:为便于维护,需要提前驱逐node节点

7.kubectl taint命令
功能:更新一个或多个 node 节点的污点信息

五、Settings Commands 设置命令
1.kubectl lable命令
http://docs.kubernetes.org.cn/628.html
功能:更新(增加、修改或删除)资源上的 label(标签)。
label 必须以字母或数字开头,可以使用字母、数字、连字符、点和下划线,最长63个字符。
如果--overwrite 为 true,则可以覆盖已有的 label,否则尝试覆盖 label 将会报错。
如果指定了--resource-version,则更新将使用此资源版本,否则将使用现有的资源版本。
语法:$ label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
示例:
exp1: 给名为foo的Pod添加label unhealthy=true。
kubectl label pods foo unhealthy=true
exp2: 给名为foo的Pod修改label 为 'status' / value 'unhealthy',且覆盖现有的value。
kubectl label --overwrite pods foo status=unhealthy
exp3: 给 namespace 中的所有 pod 添加 label
kubectl label pods --all status=unhealthy
exp4: 仅当resource-version=1时才更新名为foo的Pod上的label。
kubectl label pods foo status=unhealthy --resource-version=1
exp5: 删除名为“bar”的label 。(使用“ - ”减号相连)
kubectl label pods foo bar-
选项说明:

2.kubectl annotate命令
http://docs.kubernetes.org.cn/477.html
功能:更新一个或多个资源的Annotations信息。
Annotations由key/value组成。
Annotations的目的是存储辅助数据,特别是通过工具和系统扩展操作的数据,更多介绍在这里。
如果--overwrite为true,现有的annotations可以被覆盖,否则试图覆盖annotations将会报错。
如果设置了--resource-version,则更新将使用此resource version,否则将使用原有的resource version
有效资源类型包括:
all
certificatesigningrequests (aka 'csr')
clusterrolebindings
clusterroles
clusters (valid only for federation apiservers)
componentstatuses (aka 'cs')
configmaps (aka 'cm')
controllerrevisions
cronjobs
daemonsets (aka 'ds')
deployments (aka 'deploy')
endpoints (aka 'ep')
events (aka 'ev')
horizontalpodautoscalers (aka 'hpa')
ingresses (aka 'ing')
jobs
limitranges (aka 'limits')
namespaces (aka 'ns')
networkpolicies (aka 'netpol')
nodes (aka 'no')
persistentvolumeclaims (aka 'pvc')
persistentvolumes (aka 'pv')
poddisruptionbudgets (aka 'pdb')
podpreset
pods (aka 'po')
podsecuritypolicies (aka 'psp')
podtemplates
replicasets (aka 'rs')
replicationcontrollers (aka 'rc')
resourcequotas (aka 'quota')
rolebindings
roles
secrets
serviceaccounts (aka 'sa')
services (aka 'svc')
statefulsets
storageclasses
thirdpartyresources
语法:$ annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
示例:
exp1: 更新Pod“foo”,设置annotation “description”的value “my frontend”,如果同一个annotation多次设置,则只使用最后设置的value值。
kubectl annotate pods foo description='my frontend'
exp2: 根据“pod.json”中的type和name更新pod的annotation
kubectl annotate -f pod.json description='my frontend'
exp3: 更新Pod"foo",设置annotation“description”的value“my frontend running nginx”,覆盖现有的值。
kubectl annotate --overwrite pods foo description='my frontend running nginx'
exp4: 更新 namespace中的所有pod
kubectl annotate pods --all description='my frontend running nginx'
exp5: 只有当resource-version为1时,才更新pod ' foo '。
kubectl annotate pods foo description='my frontend running nginx' --resource-version=1
exp6: 通过删除名为“description”的annotations来更新pod ' foo '。#不需要- overwrite flag。
kubectl annotate pods foo description-
选项说明:

3.kubectl completion命令

六、Troubleshooting and Debugging Commands 故障排除和调试命令
1.kubectl describe命令
https://www.kubernetes.org.cn/doc-61
功能:输出指定的一个/多个资源的详细信息。
此命令组合调用多条API,输出指定的一个或者一组资源的详细描述。
$ kubectl describe TYPE NAME_PREFIX
首先检查是否有精确匹配TYPE和NAME_PREFIX的资源,如果没有,将会输出所有名称以NAME_PREFIX开头的资源详细信息。
支持的资源包括但不限于(大小写不限):pods (po)、services (svc)、 replicationcontrollers (rc)、nodes (no)、events (ev)、componentstatuses (cs)、 limitranges (limits)、persistentvolumes (pv)、persistentvolumeclaims (pvc)、 resourcequotas (quota)和secrets。
语法:
kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)
示例:
exp1: 描述一个node
$ kubectl describe nodes kubernetes-minion-emt8.c.myproject.internal
exp2: 描述一个pod
$ kubectl describe pods/nginx
exp3: 描述pod.json中的资源类型和名称指定的pod
$ kubectl describe -f pod.json
exp4: 描述所有的pod
$ kubectl describe pods
exp5: 描述所有包含label name=myLabel的pod
$ kubectl describe po -l name=myLabel
exp6: 描述所有被replication controller “frontend”管理的pod(rc创建的pod都以rc的名字作为前缀)
$ kubectl describe pods frontend
选项说明:
-f, --filename=[]: 用来指定待描述资源的文件名,目录名或者URL。
-l, --selector="": 用于过滤资源的Label。

2.kubectl logs命令
https://www.kubernetes.org.cn/doc-64
功能:输出pod中一个容器的日志。
输出pod中一个容器的日志。如果pod只包含一个容器则可以省略容器名。
语法:kubectl logs [-f] [-p] POD [-c CONTAINER]
示例:
exp1: 返回仅包含一个容器的pod nginx的日志快照
$ kubectl logs nginx
exp2: 返回pod ruby中已经停止的容器web-1的日志快照
$ kubectl logs -p -c ruby web-1
exp3: 持续输出pod ruby中的容器web-1的日志
$ kubectl logs -f -c ruby web-1
exp4: 仅输出pod nginx中最近的20条日志
$ kubectl logs --tail=20 nginx
exp5: 输出pod nginx中最近一小时内产生的所有日志
$ kubectl logs --since=1h nginx
选项说明:
-c, --container="": 容器名。
-f, --follow[=false]: 指定是否持续输出日志。
--interactive[=true]: 如果为true,当需要时提示用户进行输入。默认为true。
--limit-bytes=0: 输出日志的最大字节数。默认无限制。
-p, --previous[=false]: 如果为true,输出pod中曾经运行过,但目前已终止的容器的日志。
--since=0: 仅返回相对时间范围,如5s、2m或3h,之内的日志。默认返回所有日志。只能同时使用since和since-time中的一种。
--since-time="": 仅返回指定时间(RFC3339格式)之后的日志。默认返回所有日志。只能同时使用since和since-time中的一种。
--tail=-1: 要显示的最新的日志条数。默认为-1,显示所有的日志。
--timestamps[=false]: 在日志中包含时间戳。

3.kubectl attach命令
https://www.kubernetes.org.cn/doc-49
功能:
连接到一个正在运行的容器。
连接到现有容器中一个正在运行的进程。
语法:
kubectl attach POD -c CONTAINER
示例:
exp1: 获取正在运行中的pod 123456-7890的输出,默认连接到第一个容器
$ kubectl attach 123456-7890
exp2: 获取pod 123456-7890中ruby-container的输出
$ kubectl attach 123456-7890 -c ruby-container date
exp3: 切换到终端模式,将控制台输入发送到pod 123456-7890的ruby-container的“bash”命令,并将其输出到控制台,错误控制台的信息发送回客户端。
$ kubectl attach 123456-7890 -c ruby-container -i -t
选项
-c, --container="": 容器名。
-i, --stdin[=false]: 将控制台输入发送到容器。
-t, --tty[=false]: 将标准输入控制台作为容器的控制台输入。

4.kubectl exec命令
https://www.kubernetes.org.cn/doc-63
功能:在容器内部执行命令。
语法:kubectl exec POD [-c CONTAINER] -- COMMAND [args...]
示例:
exp1: 默认在pod 123456-7890的第一个容器中运行“date”并获取输出
$ kubectl exec 123456-7890 date
exp2: 在pod 123456-7890的容器ruby-container中运行“date”并获取输出
$ kubectl exec 123456-7890 -c ruby-container date
exp3: 切换到终端模式,将控制台输入发送到pod 123456-7890的ruby-container的“bash”命令,并将其输出到控制台/
# 错误控制台的信息发送回客户端。
$ kubectl exec 123456-7890 -c ruby-container -i -t -- bash -il
选项
-c, --container="": 容器名。如果未指定,使用pod中的一个容器。
-p, --pod="": Pod名。
-i, --stdin[=false]: 将控制台输入发送到容器。
-t, --tty[=false]: 将标准输入控制台作为容器的控制台输入。

5.kubectl port-forward命令
功能:
语法:kubectl port-forward
选项:
示例:

6.kubectl proxy命令
功能:创建一个代理服务器,或者一个应用程序网关。
语法:kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [options]
选项:
示例:

7.kubectl cp命令
功能:从容器向外拷贝文件或目录,或者向容器内拷贝文件或目录。
语法:kubectl cp <file-spec-src> <file-spec-dest> [options]
选项:
-c, --container='': 指定容器名。如果未指定时,则默认指定Pod内的第一个容器。
--no-preserve=false: 拷贝文件的所有者和权限保存/不保存在容器中。
示例:
exp1: 向容器内拷贝目录
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
exp2: 向指定容器内拷贝文件
kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>
exp3: 向指定命名空间下的容器内拷贝文件
kubectl cp /tmp/foo <some-pod>:/tmp/bar -n <some-namespace>
exp4: 将指定命名空间下容器内的文件拷贝到本地
kubectl cp <some-pod>:/tmp/bar /tmp/foo -n <some-namespace>

8.kubectl auth命令
功能:Inspect authorization检查授权
语法:kubectl auth

七、Advanced Commands高级命令
1.kubectl patch命令
http://docs.kubernetes.org.cn/632.html
功能:使用(patch)补丁修改、更新资源的字段。支持JSON和YAML格式。
语法:kubectl patch (-f FILENAME | TYPE NAME) -p PATCH
示例:
exp1: 使用patch更新Node节点。
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
exp2: 使用patch更新由“node.json”文件中指定的类型和名称标识的节点
kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}'
exp3: 更新容器的镜像
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'
选项:
--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 identifying the resource to update
--include-extended-apis=true: If true, include definitions of new APIs via calls to the API server. [default true]
--local=false: If true, patch will operate on the content of the file, not the server-side resource.
--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-version : DEPRECATED: To use a specific API version, fully-qualify the resource, version, and group (for example: 'jobs.v1.batch/myjob').
-p, --patch: The patch to be applied to the resource JSON 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.
-a, --show-all=false: When printing, show all resources (default hide terminated pods.)
--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].
--type=strategic: The type of patch being provided; one of [json merge strategic]

2.kubectl replace命令
http://docs.kubernetes.org.cn/635.html
功能:使用配置文件或stdin来替换资源。支持JSON和YAML格式。
如果替换当前资源,则必须提供完整的资源规范。完整的资源规范可以通过以下命令获取:kubectl get TYPE NAME -o yaml
语法:kubectl replace -f FILENAME
示例:
exp1: 使用pod.json中的数据替换pod。
kubectl replace -f ./pod.json
exp2: 根据传入的JSON替换pod。
cat pod.json | kubectl replace -f -
exp3: 更新镜像版本(tag)到v4
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
exp4: 强制替换,删除原有资源,然后重新创建资源
kubectl replace --force -f ./pod.json
选项:
--cascade=false: Only relevant during a force replace. If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController).
-f, --filename=[]: Filename, directory, or URL to files to use to replace the resource.
--force=false: Delete and re-create the specified resource
--grace-period=-1: Only relevant during a force replace. Period of time in seconds given to the old resource to terminate gracefully. Ignored if negative.
--include-extended-apis=true: If true, include definitions of new APIs via calls to the API server. [default true]
-o, --output: Output mode. Use "-o name" for shorter output (resource/name).
--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.
--schema-cache-dir=~/.kube/schema: If non-empty, load/store cached API schemas in this directory, default is '$HOME/.kube/schema'
--timeout=0s: Only relevant during a force replace. The length of time to wait before giving up on a delete of the old resource, zero means determine a timeout from the size of the object. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).
--validate=true: If true, use a schema to validate the input before sending it

3.kubectl convert命令
http://docs.kubernetes.org.cn/488.html
功能:
转换配置文件为不同的API版本,支持YAML和JSON格式。
该命令将配置文件名,目录或URL作为输入,并将其转换为指定的版本格式,如果目标版本未指定或不支持,则转换为最新版本。
默认输出将以YAML格式打印出来,可以使用- o选项改变输出格式。
语法:kubectl convert -f FILENAME
示例:
exp1: 将“pod.yaml”转换为最新版本并打印到stdout。
kubectl convert -f pod.yaml
exp2: 将“pod.yaml”指定的资源的实时状态转换为最新版本#,并以json格式打印到stdout。
kubectl convert -f pod.yaml --local -o json
exp3: 将当前目录下的所有文件转换为最新版本,并将其全部创建。
kubectl convert -f . | kubectl create -f -
选项:
--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 need to get converted.
--include-extended-apis=true: If true, include definitions of new APIs via calls to the API server. [default true]
--local=true: If true, convert will NOT try to contact api-server but run locally.
--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-version : Output the formatted object with the given group version (for ex: 'extensions/v1beta1').)
-R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
--schema-cache-dir=~/.kube/schema: If non-empty, load/store cached API schemas in this directory, default is '$HOME/.kube/schema'
-a, --show-all=false: When printing, show all resources (default hide terminated pods.)
--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].
--validate=true: If true, use a schema to validate the input before sending it

4.kubectl apply命令
https://blog.csdn.net/bbwangj/article/details/82011678
功能:通过文件名或控制台输入,对资源进行配置。接受JSON和YAML格式的描述文件。
语法:kubectl apply -f FILENAME
示例:
exp1: 将pod.json中的配置应用到pod
$ kubectl apply -f ./pod.json
exp2: 将控制台输入的JSON配置应用到Pod
$ cat pod.json | kubectl apply -f
选项:
-f, --filename=[]: 包含配置信息的文件名,目录名或者URL。
-o, --output="": 输出格式,使用“-o name”来输出简短格式(资源类型/资源名)。
--schema-cache-dir="/tmp/kubectl.schema": 如果不为空,将API schema缓存为指定文件,默认缓存到“/tmp/kubectl.schema”。
--validate[=true]: 如果为true,在发送到服务端前先使用schema来验证输入

5.kubectl diff命令
功能:比较当前配置和文件内的配置信息的差异
语法:kubectl diff -f FILENAME [options]
选项:
-f, --filename=[]:
-R, --recursive=false:
示例:
kubectl diff -f pod.json
cat service.yaml | kubectl diff -f -

6.kubectl wait命令
功能:
语法:
kubectl wait resource.group/name [--for=delete | --for condition=available] [options]
选项:
--all-namespaces=false:
--allow-missing-template-keys=true:
-f, --filename=[]:
-o, --output='':
-R, --recursive=true:
-l, selectot='':
--template='':
--timeout=30s:
示例:
kubectl wait --for=condition=Ready pod/busybox1
kubectl delete pod/busybox1
kubectl wait --for=delete pod/busybox1 --timeout=60s

八、Other Commands其他命令
1.kubectl api-resources命令
功能:显示该服务器上支持的API资源
语法:kubectl api-resources [选项]
选项:
--api-group='': Limit to resources in the specified API group
--cached=false: Use the cached list of resources if available 使用缓存的资源列表(如果可用)
--namespaced=true: 通过命名空间来限定资源, 取值:true,false,默认true。true指输出命名空间内的资源,false指输出不在命名空间内的资源。
--no-headers=false: 是否输出标题(抬头)信息。默认输出。
-o, --output='': 输出格式,取值:wide,name。wide指详细信息,name指只输出名称。
--verbs=[]: 根据支持的动作来过滤资源,动作包括:create delete deletecollection get list patch update watch
示例:
exp1: 显示支持的API资源
kubectl api-resources
exp2: 显示支持的API资源及更多信息
kubectl api-resources -o wide
exp3: 显示命名空间的API资源
kubectl api-resources --namespaced=true
exp4: 显示命名空间以外的API资源
kubectl api-resources --namespaced=false
exp5: 显示指定api-group的API资源
kubectl api-resources --api-group=extensions
exp6: 显示同时支持create和get动作的API资源
kubectl api-resources --verbs=create --verbs=get -o wide

2.kubectl api-versions命令
https://www.kubernetes.org.cn/doc-47
功能:以“组/版本”的格式输出服务端支持的API版本。
语法:kubectl api-versions

3.kubectl config命令
https://www.kubernetes.org.cn/doc-51
功能:修改kubeconfig配置文件。
使用config的子命令修改kubeconfig配置文件,如“kubectl config set current-context my-context”。
配置文件的读取遵循如下规则:
如果指定了--kubeconfig选项,那么只有指定的文件被加载。此选项只能被设置一次,并且不会合并其他文件。If the --kubeconfig flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.
如果设置了$KUBECONFIG环境变量,将同时使用此环境变量指定的所有文件列表(使用操作系统默认的顺序),所有文件将被合并。
当修改一个值时,将修改设置了该值的文件。当创建一个值时,将在列表的首个文件创建该值。
若列表中所有的文件都不存在,将创建列表中的最后一个文件。
如果前两项都没有设置,将使用 ${HOME}/.kube/config,并且不会合并其他文件。
语法:kubectl config SUBCOMMAND
选项
--kubeconfig="": 使用特定的配置文件。‘
子命令:
current-context :显示current-context
delete-cluster :从kubeconfig中删除指定cluster
delete-context :从kubeconfig中删除指定context
get-clusters :显示kubeconfig中定义的cluster
get-contexts :显示kubeconfig中定义的context
rename-contexts :重命名kubeconfig中的context
set :在kubeconfig中设置一个单独的值
set-cluster :kubeconfig中设置cluster
set-context :kubeconfig中设置context
set-credentials :kubeconfig中设置用户
unset :在kubeconfig中取消一个单独的值
use-context :kubeconfig中设置当前context
view :显示指定kubeconfig文件或合并kubeconfig设置

2.1 kubectl config current-context :显示current-context
2.2 kubectl config delete-cluster :从kubeconfig中删除指定cluster
2.3 kubectl config delete-context :从kubeconfig中删除指定context
2.4 kubectl config get-clusters :显示kubeconfig中定义的cluster
2.5 kubectl config get-contexts :显示kubeconfig中定义的context
2.6 kubectl config rename-contexts :重命名kubeconfig中的context
2.7 kubectl config set :在kubeconfig中设置一个单独的值
2.8 kubectl config set-cluster :kubeconfig中设置cluster
2.9 kubectl config set-context :kubeconfig中设置context
2.10 kubectl config set-credentials :kubeconfig中设置用户
2.11 kubectl config unset :在kubeconfig中取消一个单独的值
2.12 kubectl config use-context :kubeconfig中设置当前context
2.13 kubectl config view :显示指定kubeconfig文件或合并kubeconfig设置

4.kubectl plugin命令

5.kubectl version命令
https://www.kubernetes.org.cn/doc-65
功能:输出服务端和客户端的版本信息。
语法:kubectl version
选项:
--client[=false]: 仅输出客户端版本(无需连接服务器)。
--short[=false]: 仅输出版本号
-o,--output[=yaml/json]: 设置输出格式

6.kubectl help命令
https://blog.csdn.net/snail0li/article/details/79281123
功能:获得特定命令的帮助信息。
语法:
kubectl
kubectl help
kubectl --help
kubectl 子命令 --help

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!