kubectl命令详解

Kubernetes kubectl 命令表

“一劳永逸” 的话,有是有的,而 “一劳永逸” 的事却极少

kubectl run

  • 创建并运行一个或者多个容器镜像

  • 创建一个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

其它详细说明

NameShorthandDefaultUsage
allow-missing-template-keystrueIf 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.
attachfalseIf true, wait for the Pod to start running, and then attach to the Pod as if ‘kubectl attach …’ were called. Default false, unless ‘-i/–stdin’ is set, in which case the default is true. With ‘–restart=Never’ the exit code of the container process is returned.
commandfalseIf true and extra arguments are present, use them as the ‘command’ field in the container, rather than the ‘args’ field which is the default.
dry-runfalseIf true, only print the object that would be sent, without sending it.
env[]Environment variables to set in the container
exposefalseIf true, a public, external service is created for the container(s) which are run
generatorThe name of the API generator to use, see http://kubernetes.io/docs/user-guide/kubectl-conventions/#generators for a list.
hostport-1The host port mapping for the container port. To demonstrate a single-machine container.
imageThe image for the container to run.
image-pull-policyThe image pull policy for the container. If left empty, this value will not be specified by the client and defaulted by the server
include-extended-apistrueIf true, include definitions of new APIs via calls to the API server. [default true]
labelslLabels to apply to the pod(s).
leave-stdin-openfalseIf the pod is started in interactive mode or with stdin, leave stdin open after the first attach completes. By default, stdin will be closed after the first attach completes.
limitsThe resource requirement limits for this container. For example, ‘cpu=200m,memory=512Mi’. Note that server side components may assign limits depending on the server configuration, such as limit ranges.
no-headersfalseWhen using the default or custom-column output format, don’t print headers (default print headers).
outputoOutput 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-versionDEPRECATED: To use a specific API version, fully-qualify the resource, version, and group (for example: ‘jobs.v1.batch/myjob’).
overridesAn inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field.
pod-running-timeout1m0sThe length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running
portThe port that this container exposes. If --expose is true, this is also the port used by the service that is created.
quietfalseIf true, suppress prompt messages.
recordfalseRecord 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.
replicasr1Number of replicas to create for this container. Default is 1.
requestsThe resource requirement requests for this container. For example, ‘cpu=100m,memory=256Mi’. Note that server side components may assign requests depending on the server configuration, such as limit ranges.
restartAlwaysThe restart policy for this Pod. Legal values [Always, OnFailure, Never]. If set to ‘Always’ a deployment is created, if set to ‘OnFailure’ a job is created, if set to ‘Never’, a regular pod is created. For the latter two --replicas must be 1. Default ‘Always’, for CronJobs Never.
rmfalseIf true, delete resources created in this command for attached containers.
save-configfalseIf 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.
scheduleA schedule in the Cron format the job should be run with.
service-generatorservice/v2The name of the generator to use for creating a service. Only used if --expose is true
service-overridesAn inline JSON override for the generated service object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field. Only used if --expose is true.
show-allafalseWhen printing, show all resources (default hide terminated pods.)
show-labelsfalseWhen printing, show all labels as the last column (default hide labels column)
sort-byIf 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.
stdinifalseKeep stdin open on the container(s) in the pod, even if nothing is attached.
templateTemplate 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].
ttytfalseAllocated a TTY for each container in the pod.

kubectl expose

将资源暴露为新的 Kubernetes service

指定deployment、service、replica setreplication controllerpod ,并使用该资源的选择器作为指定端口上新服务的选择器。deployment 或 replica set只有当其选择器可转换为service支持的选择器时,即当选择器仅包含matchLabels组件时才会作为暴露新的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]

kubectl annotate

更新一个或者多个资源的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]

示例

更新Pod“foo”,设置annotation “description”的value “my frontend”,如果同一个annotation多次设置,则只使用最后设置的value值。

kubectl annotate pods foo description='my frontend'

根据“pod.json”中的type和name更新pod的annotation

kubectl annotate -f pod.json description='my frontend'

更新Pod"foo",设置annotation“description”的value“my frontend running nginx”,覆盖现有的值。

kubectl annotate --overwrite pods foo description='my frontend running nginx'

更新 namespace中的所有pod

kubectl annotate pods --all description='my frontend running nginx'

只有当resource-version为1时,才更新pod ’ foo '。

kubectl annotate pods foo description='my frontend running nginx' --resource-version=1

通过删除名为“description”的annotations来更新pod ’ foo '。#不需要- overwrite flag。

kubectl annotate pods foo description-

kubectl autoscale

使用 autoscaler 自动设置在kubernetes集群中运行的pod数量(水平自动伸缩)。

指定Deployment、ReplicaSet或ReplicationController,并创建已经定义好资源的自动伸缩器。使用自动伸缩器可以根据需要自动增加或减少系统中部署的pod数量。

语法

$ autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]

示例

使用 Deployment “foo”设定,使用默认的自动伸缩策略,指定目标CPU使用率,使其Pod数量在2到10之间。

kubectl autoscale deployment foo --min=2 --max=10

使用RC“foo”设定,使其Pod的数量介于1和5之间,CPU使用率维持在80%。

kubectl autoscale rc foo --max=5 --cpu-percent=80

kubectl convert

转换配置文件为不同的API版本,支持YAML和JSON格式。

该命令将配置文件名,目录或URL作为输入,并将其转换为指定的版本格式,如果目标版本未指定或不支持,则转换为最新版本。

默认输出将以YAML格式打印出来,可以使用- o选项改变输出格式。

语法

$ convert -f FILENAME

示例

将“pod.yaml”转换为最新版本并打印到stdout。

kubectl convert -f pod.yaml

将“pod.yaml”指定的资源的实时状态转换为最新版本#,并以json格式打印到stdout。

kubectl convert -f pod.yaml --local -o json

将当前目录下的所有文件转换为最新版本,并将其全部创建。

kubectl convert -f . | kubectl create -f -

kubectl create

通过配置文件名或 stdin ( 标准输入流) 创建一个集群资源对象

支持JSON和YAML格式的文件。

语法

$ create -f FILENAME

示例

通过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

kubectl create clusterrole

创建一个ClusterRole。

语法

$ clusterrole NAME --verb=verb --resource=resource.group [--resource-name=resourcename] [--dry-run]

示例

创建一个名为“pod-reader”的ClusterRole,允许用户在pod上执行“get”,“watch”和“list”

kubectl create clusterrole pod-reader --verb=get,list,watch --resource=pods

创建一个名为“pod-reader”的ClusterRole,其中指定了ResourceName

kubectl create clusterrole pod-reader --verb=get,list,watch --resource=pods --resource-name=readablepod --resource-name=anotherpod

在指定的API Group中创建为"foo"的ClusterRole

kubectl create clusterrole foo --verb=get,list,watch --resource=rs.extensions

创建一个名为“foo”的ClusterRole,并指定SubResource

kubectl create clusterrole foo --verb=get,list,watch --resource=pods,pods/status

使用指定的NonResourceURL创建名称“foo”的ClusterRole

kubectl create clusterrole "foo" --verb=get --non-resource-url=/logs/*

kubectl create clusterrolebinding

为特定的ClusterRole创建ClusterRoleBinding。

语法

$ clusterrolebinding NAME --clusterrole=NAME [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run]

示例

在集群范围将cluster-admin ClusterRole授予用户user1,user2和group1。

kubectl create clusterrolebinding cluster-admin --clusterrole=cluster-admin --user=user1 --user=user2 --group=group1

kubectl create configmap

根据配置文件、目录或指定的literal-value创建configmap 。

configmap 用来保存一个或多个key/value信息。

当基于配置文件创建configmap时,key将默认为文件的基础名称,value默认为文件文本内容。如果基本名称的key无效,则可以指定另一个key。

当基于目录创建configmap时,key还是文件的基础名称,目录中每个配置文件名都被设置为key,文件内容设置为value。

语法

$ configmap NAME [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]

示例

根据文件创建一个名为my-config的configmap

kubectl create configmap my-config --from-file=path/to/bar

使用指定的keys创建一个名为my-config的configmap

kubectl create configmap my-config --from-file=key1=/path/to/bar/file1.txt --from-file=key2=/path/to/bar/file2.txt

使用key1 = config1和key2 = config2创建一个名为my-config的configmap

kubectl create configmap my-config --from-literal=key1=config1 --from-literal=key2=config2

从文件中的key = value对创建一个名为my-config的configmap

kubectl create configmap my-config --from-file=path/to/bar

从env文件创建一个名为my-config的configmap

kubectl create configmap my-config --from-env-file=path/to/bar.env

kubectl create deployment

创建具有指定名称的deployment 。

语法

$ deployment NAME --image=image [--dry-run]

示例

创建一个名为my-dep的deployment,运行busybox镜像。

kubectl create deployment my-dep --image=busybox

kubectl create namespace

创建一个具有指定名称的namespace。

语法

$ namespace NAME [--dry-run]

示例

创建一个名为my-namespace的namespace

kubectl create namespace my-namespace

创建名为my-pdb的pod disruption budget,使用app = nginx label #选择所有pod,要求至少**50%**Pod可用。

kubectl create pdb my-pdb --selector=app=nginx --min-available=50%

kubectl create poddisruptionbudget

使用指定的name、selector和所需的最小pod数量,创建一个pod disruption budget。

语法

$ poddisruptionbudget NAME --selector=SELECTOR --min-available=N [--dry-run]

示例

创建名为my-pdb的pod disruption budget,使用app = rails label #来选择所有pod,要求至少1个Pod可用。

kubectl create poddisruptionbudget my-pdb --selector=app=rails --min-available=1

创建名为my-pdb的pod disruption budget,使用app = nginx label #选择所有pod,要求至少**50%**Pod可用。

kubectl create pdb my-pdb --selector=app=nginx --min-available=50%

kubectl create quota

创建具有指定名称、hard限制和可选scopes的resourcequota

语法

$ quota NAME [--hard=key1=value1,key2=value2] [--scopes=Scope1,Scope2] [--dry-run=bool]

示例

创建名为my-quota的resourcequota

kubectl create quota my-quota --hard=cpu=1,memory=1G,pods=2,services=3,replicationcontrollers=2,resourcequotas=1,secrets=5,persistentvolumeclaims=10

创建名为best-effort的resourcequota

kubectl create quota best-effort --hard=pods=100 --scopes=BestEffort

kubectl create role

使用单一规则创建Role。

语法

$ role NAME --verb=verb --resource=resource.group/subresource [--resource-name=resourcename] [--dry-run]

示例

创建名为“pod-reader”的Role ,允许用户在pod上执行“get”,“watch”和“list”

kubectl create role pod-reader --verb=get --verb=list --verb=watch --resource=pods

创建名为“pod-reader”的Role,并指定ResourceName

kubectl create role pod-reader --verb=get,list,watch --resource=pods --resource-name=readablepod --resource-name=anotherpod

使用指定的API Group 创建名为“foo”的Role

kubectl create role foo --verb=get,list,watch --resource=rs.extensions

使用指定的SubResource创建名为“foo”的Role

kubectl create role foo --verb=get,list,watch --resource=pods,pods/status

kubectl create rolebinding

为特定Role或ClusterRole创建RoleBinding。

语法

$ rolebinding NAME --clusterrole=NAME|--role=NAME [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run]

示例

将admin ClusterRole授予user1,user2和group1。

kubectl create rolebinding admin --clusterrole=admin --user=user1 --user=user2 --group=group1

、kubectl create service

使用指定的子命令创建 Service服务。

语法

$ service

kubectl create service clusterip

创建具有指定Service名的clusterIP。

语法

$ clusterip NAME [--tcp=<port>:<targetPort>] [--dry-run]

示例

创建Service名为my-cs为的clusterIP

kubectl create service clusterip my-cs --tcp=5678:8080

创建Service名为my-cs的clusterIP(headless模式)

kubectl create service clusterip my-cs --clusterip="None"

kubectl create service externalname

创建指定Service名的ExternalName。

语法

$ externalname NAME --external-name external.name [--dry-run]

示例

创建Service名为my-ns的ExternalName

kubectl create service externalname my-ns --external-name bar.com

kubectl create service loadbalancer

创建一个指定名称的Service的LoadBalancer。

语法

$ loadbalancer NAME [--tcp=port:targetPort] [--dry-run]

示例

创建一个Service名为my-lbs的LoadBalancer。

kubectl create service loadbalancer my-lbs --tcp=5678:8080

kubectl create service nodeport

创建指定Service名称的nodeport。

语法

$ nodeport NAME [--tcp=port:targetPort] [--dry-run]

示例

创建service名为my-ns的新的nodeport。

kubectl create service nodeport my-ns --tcp=5678:8080

kubectl create serviceaccount

创建指定名称的service account。

语法

$ serviceaccount NAME [--dry-run]

示例

创建一个名为my-service-account的 service account

kubectl create serviceaccount my-service-account

kubectl create secret

使用指定的子命令创建 secret。

语法

$ secret

create secret tls

从给定的(public/private)公钥/私钥对创建TLS secret 。

公共密钥证书必须是.PEM编码并匹配指定的私钥。

语法

$ tls NAME --cert=path/to/cert/file --key=path/to/key/file [--dry-run]

示例

使用指定的key创建名为tls-secret的TLS secret :

kubectl create secret tls tls-secret --cert=path/to/tls.cert --key=path/to/tls.key

kubectl create secret generic

根据配置文件、目录或指定的literal-value创建secret。

secret可以保存为一个或多个key/value信息。

当基于配置文件创建secret时,key将默认为文件的基础名称,value默认为文件内容。如果基本名称的key无效,则可以指定另一个key。

当基于目录创建secret时,key还是文件的基础名称,目录中有效的key的每个文件都被打包到secret中,除了常规文件之外的任何目录条目都被忽略(例如subdirectories, symlinks, devices, pipes, etc)。

语法

$ generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]

示例

使用指定的keys创建一个名为my-secret的secret

kubectl create secret generic my-secret --from-file=ssh-privatekey=~/.ssh/id_rsa --from-file=ssh-publickey=~/.ssh/id_rsa.pub

用key1 = supersecret和key2 = topsecret创建一个名为my-secret的secret

kubectl create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecret

从env文件创建名为my-secret的secret

kubectl create secret generic my-secret --from-env-file=path/to/bar.env

kubectl create secret docker-registry

创建与Docker registries一起使用的secret。

Dockercfg secrets用于对Docker registries进行安全认证。

当使用Docker命令push镜像时,可以进行Docker registries认证

$ docker login DOCKER_REGISTRY_SERVER --username=DOCKER_USER --password=DOCKER_PASSWORD --email=DOCKER_EMAIL'.

这时会产生一个 ~/.dockercfg 文件,在“docker push”和“docker pull”命令时,此文件用于registries进行认证。

在创建应用时,当Node节点从私有仓库Pull镜像时,需要有相应凭证,才能使用私有Docker仓库。我们可以通过创建dockercfg secret并添加到service account来实现。

语法

$ docker-registry NAME --docker-username=user --docker-password=password --docker-email=email [--docker-server=string] [--from-literal=key1=value1] [--dry-run]

示例

如果没有.dockercfg 文件,则可以使用以下命令创建dockercfg secret:

kubectl create secret docker-registry my-secret --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL

kubectl delete

通过配置文件名、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)])

示例

使用 pod.json中指定的资源类型和名称删除pod。

kubectl delete -f ./pod.json

根据传入stdin的JSON所指定的类型和名称删除pod。

cat pod.json | kubectl delete -f -

删除名为“baz”和“foo”的Pod和Service。

kubectl delete pod,service baz foo

删除 Label name = myLabel的pod和Service。

kubectl delete pods,services -l name=myLabel

强制删除dead node上的pod

kubectl delete pod foo --grace-period=0 --force

删除所有pod

kubectl delete pods --all

kubectl edit

使用默认编辑器 编辑服务器上定义的资源。

使用命令行工具获取的任何资源都可以使用edit命令编辑。edit命令会打开使用KUBE_EDITOR,GIT_EDITOR 或者EDITOR环境变量定义的编辑器,可以同时编辑多个资源,但所编辑过的资源只会一次性提交。edit除命令参数外还接受文件名形式。

文件默认输出格式为YAML。要以JSON格式编辑,请指定“-o json”选项。

如果在更新资源时报错,将会在磁盘上创建一个临时文件来记录。在更新资源时最常见的错误是几个用户同时使用编辑器更改服务器上资源,发生这种情况,你需要将你的更改应用到最新版本的资源上,或者更新保存的临时副本。

语法

$ edit (RESOURCE/NAME | -f FILENAME)

示例

编辑名为’docker-registry’的service:

kubectl edit svc/docker-registry

使用替代的编辑器

KUBE_EDITOR="nano" kubectl edit svc/docker-registry

编辑名为“myjob”的service,输出JSON格式 V1 API版本

kubectl edit job.v1.batch/myjob -o json

以YAML格式输出编辑deployment“mydeployment”,并将修改的配置保存在annotation中:

kubectl edit deployment/mydeployment -o yaml --save-config

kubectl get

获取列出一个或多个资源的信息。

可以使用的资源包括:

  • 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]

示例

列出所有运行的Pod信息。

kubectl get pods

列出Pod以及运行Pod节点信息。

kubectl get pods -o wide

列出指定NAME的 replication controller信息。

kubectl get replicationcontroller web

以JSON格式输出一个pod信息。

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

以“pod.yaml”配置文件中指定资源对象和名称输出JSON格式的Pod信息。

kubectl get -f pod.yaml -o json

返回指定pod的相位值。

kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}

列出所有replication controllers和service信息。

kubectl get rc,services

按其资源和名称列出相应信息。

kubectl get rc/web service/frontend pods/web-pod-13je7

列出所有不同的资源对象。

kubectl get all

kubectl label

更新(增加、修改或删除)资源上的 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]

示例

给名为foo的Pod添加label unhealthy=true。

kubectl label pods foo unhealthy=true

给名为foo的Pod修改label 为 ‘status’ / value ‘unhealthy’,且覆盖现有的value。

kubectl label --overwrite pods foo status=unhealthy

给 namespace 中的所有 pod 添加 label

kubectl label pods --all status=unhealthy

仅当resource-version=1时才更新 名为foo的Pod上的label。

kubectl label pods foo status=unhealthy --resource-version=1

删除名为“bar”的label 。(使用“ - ”减号相连)

kubectl label pods foo bar-

kubectl patch

使用(patch)补丁修改、更新资源的字段。

支持JSON和YAML格式。

请参阅https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html中说明,查找资源字段是否为可变的。

语法

$ patch (-f FILENAME | TYPE NAME) -p PATCH

示例

使用patch更新Node节点。

kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'

使用patch更新由“node.json”文件中指定的类型和名称标识的节点

kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}'

更新容器的镜像

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"}]'

kubectl replace

使用配置文件或stdin来替换资源。

支持JSON和YAML格式。如果替换当前资源,则必须提供完整的资源规范。可以通过以下命令获取:

$ kubectl get TYPE NAME -o yaml

请参考https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html中的模型,查找字段是否为可变的。

语法

$ replace -f FILENAME

示例

使用pod.json中的数据替换pod。

kubectl replace -f ./pod.json

根据传入的JSON替换pod。

cat pod.json | kubectl replace -f -

更新镜像版本(tag)到v4

kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -

强制替换,删除原有资源,然后重新创建资源

kubectl replace --force -f ./pod.json

kubectl replace

使用配置文件或stdin来替换资源。

支持JSON和YAML格式。如果替换当前资源,则必须提供完整的资源规范。可以通过以下命令获取:

$ kubectl get TYPE NAME -o yaml

请参考https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html中的模型,查找字段是否为可变的。

语法

$ replace -f FILENAME

示例

使用pod.json中的数据替换pod。

kubectl replace -f ./pod.json

根据传入的JSON替换pod。

cat pod.json | kubectl replace -f -

更新镜像版本(tag)到v4

kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -

强制替换,删除原有资源,然后重新创建资源

kubectl replace --force -f ./pod.json

kubectl rolling-update

执行指定ReplicationController的滚动更新。

该命令创建了一个新的RC, 然后一次更新一个pod方式逐步使用新的PodTemplate,最终实现Pod滚动更新,new-controller.json需要与之前RC在相同的namespace下。

!http://kubernetes.io/images/docs/kubectl_rollingupdate.svg

语法

$ rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE | -f NEW_CONTROLLER_SPEC)

示例

使用frontend-v2.json中的新RC数据更新frontend-v1的pod。

kubectl rolling-update frontend-v1 -f frontend-v2.json

使用JSON数据更新frontend-v1的pod。

cat frontend-v2.json | kubectl rolling-update frontend-v1 -f -

其他

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

kubectl rollout

对资源进行管理

可用资源包括:

  • deployments
  • daemonsets

子命令

语法

$ rollout SUBCOMMAND

示例

回滚到之前的deployment

kubectl rollout undo deployment/abc

查看daemonet的状态

kubectl rollout status daemonset/foo

kubectl scale

扩容或缩容 Deployment、ReplicaSet、Replication Controller或 Job 中Pod数量。

scale也可以指定多个前提条件,如:当前副本数量或 --resource-version ,进行伸缩比例设置前,系统会先验证前提条件是否成立。

语法

$ scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)

示例

将名为foo中的pod副本数设置为3。

kubectl scale --replicas=3 rs/foo

将由“foo.yaml”配置文件中指定的资源对象和名称标识的Pod资源副本设为3。

kubectl scale --replicas=3 -f foo.yaml

如果当前副本数为2,则将其扩展至3。

kubectl scale --current-replicas=2 --replicas=3 deployment/mysql

设置多个RC中Pod副本数量。

kubectl scale --replicas=5 rc/foo rc/bar rc/baz

kubectl set

配置应用资源。

使用这些命令能帮你更改现有应用资源一些信息。

语法

$ set SUBCOMMAND

子命令

  • image
  • resources
  • selector
  • subject

kubectl set resources

资源对象中的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 --loca

kubectl set selector

设置资源的selector(选择器)。如果在调用"set selecto"命令之前已经存在选择器,则新创建的选择器将覆盖原来的选择器。

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 -

kubectl set image

更新现有的资源对象的容器镜像。

可使用资源对象包括(不区分大小写):

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

更新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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值