Kubectl Common Commands

Kubectl Common Commands

Kubectl common parameter classification

Basic commands: create, delete, get, run, expose, set, explain, edit

create command : create resources based on files or input

# 创建Deployment和Service资源

$ kubectl create -f demo-deployment.yaml
$ kubectl create -f demo-service.yaml

delete command : delete resources

# 根据yaml文件删除对应的资源,但是yaml文件并不会被删除,这样更加高效

$ kubectl delete -f demo-deployment.yaml 
$ kubectl delete -f demo-service.yaml

# 也可以通过具体的资源名称来进行删除,使用这个删除资源,同时删除deployment和service资源

$ kubectl delete 具体的资源名称

get command : get resource information

# 查看所有的资源信息
$ kubectl get all
$ kubectl get --all-namespaces

# 查看pod列表
$ kubectl get pod

# 显示pod节点的标签信息
$ kubectl get pod --show-labels

# 根据指定标签匹配到具体的pod
$ kubectl get pods -l app=example

# 查看node节点列表
$ kubectl get node 

# 显示node节点的标签信息
$ kubectl get node --show-labels

# 查看pod详细信息,也就是可以查看pod具体运行在哪个节点上(ip地址信息)
$ kubectl get pod -o wide

# 查看服务的详细信息,显示了服务名称,类型,集群ip,端口,时间等信息
$ kubectl get svc
$ kubectl get svc -n kube-system

# 查看命名空间
$ kubectl get ns
$ kubectl get namespaces

# 查看所有pod所属的命名空间
$ kubectl get pod --all-namespaces

# 查看所有pod所属的命名空间并且查看都在哪些节点上运行
$ kubectl get pod --all-namespaces  -o wide

# 查看目前所有的replica set,显示了所有的pod的副本数,以及他们的可用数量以及状态等信息
$ kubectl get rs

# 查看已经部署了的所有应用,可以看到容器,以及容器所用的镜像,标签等信息
$ kubectl get deploy -o wide
$ kubectl get deployments -o wide

run command : Create and run one or more container images in the cluster.

语法:run NAME --image=image [–env=“key=value”] [–port=port] [–replicas=replicas] [–dry-run=bool] [–overrides=inline-json] [–command] – [COMMAND] [args…]

# 示例,运行一个名称为nginx,副本数为3,标签为app=example,镜像为nginx:1.10,端口为80的容器实例

$ kubectl run nginx --replicas=3 --labels="app=example" --image=nginx:1.10 --port=80

# 示例,运行一个名称为nginx,副本数为3,标签为app=example,镜像为nginx:1.10,端口为80的容器实例,并绑定到k8s-node1上
$ kubectl run nginx --image=nginx:1.10 --replicas=3 --labels="app=example" --port=80 --overrides='{"apiVersion":"apps/v1","spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname":"k8s-node1"}}}}}'

更详细用法参见http://docs.kubernetes.org.cn/468.html

Expose command : create a service service, and expose the port for external access

# 创建一个nginx服务并且暴露端口让外界可以访问

$ kubectl expose deployment nginx --port=88 --type=NodePort --target-port=80 --name=nginx-service

更多expose详细用法参见http://docs.kubernetes.org.cn/475.html

set command : configure some specific resources of the application, or modify the existing resources of the application

Use kubectl set --helpview, its envsub-commands, image, resources, selector, serviceaccount, subject, .

语法:resources (-f FILENAME | TYPE NAME) ([–limits=LIMITS & --requests=REQUESTS]

set 命令详情参见http://docs.kubernetes.org.cn/669.html

kubectl set resources command

This command is used to set some scope limits for resources.

The Pod in the resource object can specify the computing resource requirements (CPU-unit m, memory-unit Mi), that is, the minimum resource request (Requests) used, the maximum resource requirement of the limit (Limits), and the Pod will guarantee the number of resources used in the setting range.

For each Pod resource, if the Limits(limit) value is specified and Requests(request) is omitted , the Requestsdefault Limitsvalue is.

可用资源对象包括(支持大小写)replicationcontrollerdeploymentdaemonsetjobreplicaset

例如

# 将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

kubectl set selector command

Set the resource's selector(selector). If there is a selector before calling the "set selector" command, the newly created selector will overwrite the original selector.

selectorIt must start with a letter or number and contain up to 63 characters. You can use: letters, numbers, hyphens "-", dot ". "and underscore" _ ". If -resource-version is specified, the update will use this resource version, otherwise the existing resource version will be used.

注意: Currently the selectorcommand can only be used for Serviceobjects.

语法:selector (-f FILENAME | TYPE NAME) EXPRESSIONS [–resource-version=version]

kubectl set image command

The container image used to update existing resources.

Resources available objects pod (po)include: 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

explain command : used to display resource document information

$ kubectl explain rs

edit command : used to edit resource information

# 编辑Deployment nginx的一些信息
$ kubectl edit deployment nginx

# 编辑service类型的nginx的一些信息
$ kubectl edit service/nginx

Setting commands: label, annotate, completion

label command : used to update (add, modify or delete) the label on the resource

  • label It must start with a letter or number. You can use letters, numbers, hyphens, dots, and underscores. The maximum length is 63 characters.
  • If --overwriteis true, you can override existing label, or the attempt to cover labelwould be an error.
  • If specified --resource-version, the update will use this resource version, otherwise the existing resource version will be used.

语法: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-

annotate command : Update Annotations information for one or more resources. It is the annotation information, you can easily check what operations have been done.

  • AnnotationsIt is composed of key/value.
  • AnnotationsThe purpose of is to store auxiliary data, especially data operated by tools and system expansion. More introduction here .
  • If --overwriteas trueexisting annotationscan be covered, otherwise attempt to cover annotationswould be an error.
  • If set --resource-version, the update will use this resource version, otherwise the original will be used resource version.

语法: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-

completion command : used to set the automatic completion of kubectl commands

BASH

# 在 bash 中设置当前 shell 的自动补全,要先安装 bash-completion 包
$ source <(kubectl completion bash)

# 在您的 bash shell 中永久的添加自动补全
$ echo "source <(kubectl completion bash)" >> ~/.bashrc

ZSH

# 在 zsh 中设置当前 shell 的自动补全
$ source <(kubectl completion zsh)  

# 在您的 zsh shell 中永久的添加自动补全
$ echo "if [ $commands[kubectl] ]; then source <(kubectl completion zsh); fi" >> ~/.zshrc

kubectl deployment commands: rollout, rolling-update, scale, autoscale

rollout command : used to manage resources

Available resources include: deployments, daemonsets.

子命令

  • history(View historical version)
  • pause(Suspend resources)
  • resume(Resume suspended resources)
  • status(View resource status)
  • undo(Rolled version)
# 语法
$ kubectl rollout SUBCOMMAND

# 回滚到之前的deployment
$ kubectl rollout undo deployment/abc

# 查看daemonet的状态
$ kubectl rollout status daemonset/foo

rolling-update command : Execute the rolling update of the specified ReplicationController.

This command creates a new one RC, and then updates it one at a time pod. It gradually uses the new one PodTemplate, and finally realizes the Podrolling update, which new-controller.jsonneeds to be RCthe same as before namespace.

语法: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

scale command : volume reduction or expansion Deployment, ReplicaSet, Replication Controlleror Jobin Podthe number of

scaleYou can also specify multiple prerequisites, such as the current number of copies or --resource-version, before setting the scaling ratio, the system will first verify whether the prerequisites are true. This is an elastic scaling strategy.

语法:kubectl scale [–resource-version=version] [–current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)

# 将名为foo中的pod副本数设置为3。
$ kubectl scale --replicas=3 rs/foo
kubectl scale deploy/nginx --replicas=30

# 将由“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

Autoscale command : This ratio is scalemore powerful and is also an elastic scaling strategy, which automatically expands or shrinks according to the amount of traffic.

Specify Deployment, ReplicaSetor ReplicationController, and create an autoscaler with defined resources. Using auto-scaler can automatically increase or decrease the number of pods deployed in the system as needed.

语法:kubectl 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

Cluster management commands: certificate, cluster-info, top, cordon, uncordon, drain, taint

certificate command : used for certificate resource management, authorization, etc.

# 例如,当有node节点要向master请求,那么是需要master节点授权的
$ kubectl certificate approve node-csr-81F5uBehyEyLWco5qavBsxc1GzFcZk3aFM3XW5rT3mw node-csr-Ed0kbFhc_q7qx14H3QpqLIUs0uKo036O2SnFpIheM18

cluster-info command : Display cluster information

$ kubectl cluster-info

top command : used to view resource usage of cpu, memory disk and other resources

# 以前需要heapster,后替换为metrics-server
$ kubectl top pod --all-namespaces

cordon command : used to mark a node unschedulable

uncordon command : for label nodes can be scheduled

The drain command : Used to exclude nodes during maintenance.

taint command : used to Nodeset a taint on a node

Cluster troubleshooting and debugging commands: describe, logs, exec, attach, port-foward, proxy, cp, auth

describe command : Display detailed information of a specific resource

# 查看my-nginx pod的详细状态
$ kubectl describe po my-nginx

logs command : used to print the log of a container in a pod. If there is only one container in the pod, the container name can be omitted

语法:kubectl logs [-f] [-p] POD [-c CONTAINER]

# 返回仅包含一个容器的pod nginx的日志快照
$ kubectl logs nginx

# 返回pod ruby中已经停止的容器web-1的日志快照
$ kubectl logs -p -c ruby web-1

# 持续输出pod ruby中的容器web-1的日志
$ kubectl logs -f -c ruby web-1

# 仅输出pod nginx中最近的20条日志
$ kubectl logs --tail=20 nginx

# 输出pod nginx中最近一小时内产生的所有日志
$ kubectl logs --since=1h nginx

参数选项

  • -c, --container="": The name of the container.
  • -f, --follow[=false]: Specify whether to output logs continuously (real-time logs).
  • –Interactive[=true]: If true, prompt the user for input when needed. The default is true.
  • --Limit-bytes=0: The maximum number of bytes in the output log. There is no limit by default.
  • -p, --previous[=false]: If true, output logs of containers that have been run in the pod, but have been terminated.
  • --Since=0: Only return logs within the relative time range, such as 5s, 2m, or 3h. All logs are returned by default. Only one of since and since-time can be used at the same time.
  • --Since-time="": Only return logs after the specified time (RFC3339 format). All logs are returned by default. Only one of since and since-time can be used at the same time.
  • --Tail=-1: The number of the latest logs to be displayed. The default is -1, which displays all logs.
  • --Timestamps[=false]: Include timestamps in the log.

exec command : enter the container to interact, execute commands in the container

语法:kubectl exec POD [-c CONTAINER] – COMMAND [args…]

命令选项

  • -c, --container="": The name of the container. If not specified, a container in the pod is used.
  • -p, --pod="": Pod名。
  • -i, --stdin[=false]: Send console input to the container.
  • -t, --tty[=false]: Use the standard input console as the container's console input.
# 进入nginx容器,执行一些命令操作
$ kubectl exec -it nginx-deployment-58d6d6ccb8-lc5fp bash

attach command : connect to a running container.

语法:kubectl attach POD -c CONTAINER

参数选项

  • -c, --container="": The name of the container. If omitted, the first pod is selected by default.
  • -i, --stdin[=false]: Send console input to the container.
  • -t, --tty[=false]: Use the standard input console as the container's console input.
# 获取正在运行中的pod 123456-7890的输出,默认连接到第一个容器
$ kubectl attach 123456-7890

# 获取pod 123456-7890中ruby-container的输出
$ kubectl attach 123456-7890 -c ruby-container

# 切换到终端模式,将控制台输入发送到pod 123456-7890的ruby-container的“bash”命令,并将其输出到控制台/
# 错误控制台的信息发送回客户端。
$ kubectl attach 123456-7890 -c ruby-container -i -t

cp command : copy files or directories to the pod container

It is used to podexchange files with external, similar to that dockerof exchanging cpthe content in the container with the external content.

Other commands: api-servions, config, help, plugin, version

api-servions command : print supported apiversion information

# 打印当前集群支持的api版本
$ kubectl api-versions

help command : used to view command help

# 显示全部的命令帮助提示
$ kubectl --help

# 具体的子命令帮助,例如
$ kubectl create --help

config command : used to modify the kubeconfigconfiguration file (used to access the api, such as configuring authentication information)

Set kubectlwith which Kubernetesa cluster communicate and modify the configuration information. View using kubeconfig across the cluster authorized to access documentation for details profile information.

# 显示合并的 kubeconfig 配置
$ kubectl config view

# 同时使用多个 kubeconfig 文件并查看合并的配置
$ KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config view

# 获取 e2e 用户的密码
$ kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'

# 展示当前所处的上下文
$ kubectl config current-context

# 设置默认的上下文为 my-cluster-name
$ kubectl config use-context my-cluster-name

# 添加新的集群配置到 kubeconf 中,使用 basic auth 进行鉴权
$ kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword

# 使用特定的用户名和命名空间设置上下文。
$ kubectl config set-context gce --user=cluster-admin --namespace=foo \
  && kubectl config use-context gce

version command : print client and server version information

# 打印客户端和服务端版本信息
$ kubectl version

plugin command : Run a command line plugin

Advanced commands: apply, patch, replace, convert

apply command : apply configuration to resources through file name or standard input

Configure resources through file name or console input. If the resource does not exist, a new one will be created. You can use JSONor YAMLformat.

语法:kubectl apply -f FILENAME

# 将pod.json中的配置应用到pod
$ kubectl apply -f ./pod.json

# 将控制台输入的JSON配置应用到Pod
$ cat pod.json | kubectl apply -f -

参数选项

  • -f, --filename=[]: File name, directory name or URL containing configuration information.
  • –include-extended-apis[=true]: If true, include definitions of new APIs via calls to the API server. [default true]
  • -o, --output="": Output mode. "-o name" is the shortcut output (resource/name).
  • --Record[=false]: Record the current kubectl command in the resource comment.
  • -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 it is not empty, the API schema will be cached as the specified file, and the default will be cached to'$HOME/.kube/schema'
  • --Validate[=true]: If true, use the schema to validate the input before sending it to the server.

patch command : use patch to modify, update the field of the resource, that is, modify part of the content of the resource

语法:kubectl patch (-f FILENAME | TYPE NAME) -p PATCH

# Partially update a node using strategic merge patch
$ kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'

# Update a container's image; spec.containers[*].name is required because it's a merge key
$ kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'

replace command : replace the original resource by file or standard input

语法:kubectl replace -f FILENAME

# Replace a pod using the data in pod.json.
$ kubectl replace -f ./pod.json

# Replace a pod based on the JSON passed into stdin.
$ cat pod.json | kubectl replace -f -

# Update a single-container pod's image version (tag) to v4
$ kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -

# Force replace, delete and then re-create the resource
$ kubectl replace --force -f ./pod.json

convert command : convert configuration files between different versions

语法:kubectl convert -f FILENAME

# Convert 'pod.yaml' to latest version and print to stdout.
$ kubectl convert -f pod.yaml

# Convert the live state of the resource specified by 'pod.yaml' to the latest version
# and print to stdout in json format.
$ kubectl convert -f pod.yaml --local -o json

# Convert all files under current directory to latest version and create them all.
$ kubectl convert -f . | kubectl create -f -

Formatted output

In a specific format to output to the terminal window details, you may -oor --outputadd parameters to the supported kubectlcommands.

![](https://img-blog.csdnimg.cn/img_convert/806cf1e60641bf5e9939d12ed0437364.png#align=left&display=inline&height=351&margin=[object Object]&originHeight=351&originWidth=977&status=done&style=none&width=977)

Kubectl log output verbosity and debugging

KubectlLog output by the level of detail -vor the --vcontrolled parameter followed by a number indicates the level of the log. KubernetesCommon habit of logging and the associated level of logging where there is a corresponding description.

![](https://img-blog.csdnimg.cn/img_convert/439120a9d2cbc26283a1855f46f055d7.png#align=left&display=inline&height=393&margin=[object Object]&originHeight=393&originWidth=1335&status=done&style=none&width=1335)

summary

These are kubectlsome of the basic commands operate, easy access when needed.

reference

Refer and organize in this original text
https://www.jianshu.com/p/07455dbfd6bb

Guess you like

Origin blog.csdn.net/qq_41489540/article/details/114216420