Post

【Cloud Native】05 K8S 命令

【Cloud Native】05 K8S 命令

重要文档

refer:

基础必会

create

  • 从文件或标准输入创建一个或多个集群资源对象。
  • 支持JSON和YAML格式的文件。
  • 创建一个全新的对象(以前不存在/已删除),要求yaml文件中的配置必须是完整的。

可以创建的资源包括不限于:

  • clusterrole
  • clusterrolebinding
  • configmap
  • deployment
  • namespace
  • poddisruptionbudget
  • quota
  • role
  • rolebinding
  • service
  • secret
1
2
3
4
5
# 创建资源
kubectl create -f xxx.yaml

# 创建test名称空间
kubectl create namespace test

⭐️ expose

  • 将资源暴露为新的Kubernetes Service。
    • 当然,可以指定类型:NodePort、ClusterIP等
  • 指定deployment、service、replica set、replication controller或pod ,并使用该资源的选择器作为指定端口上新服务的选择器。
1
2
3
4
5
6
# 为RC的nginx创建service,并通过Service的80端口转发至容器的8000端口上。
kubectl expose rc nginx --port=80 --target-port=8000

# 由“nginx-controller.yaml”中指定的type和name标识的RC创建Service,并通过Service的80端口转发至容器的8000端口上。

kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000

run

  • 创建并运行一个或多个容器镜像。
  • 创建一个deployment 或job 来管理容器。
1
2
3
4
5
6
7
8
9
10
11
# 启动nginx实例。
kubectl run nginx --image=nginx

# 启动hazelcast实例,暴露容器端口 5701。
kubectl run hazelcast --image=hazelcast --port=5701

# 启动nginx实例,设置副本数5。
kubectl run nginx --image=nginx --replicas=5

# 运行 Dry  打印相应的API对象而不创建它们。
kubectl run nginx --image=nginx --dry-run

⭐️ set

refer doc:

  • k8s中文文档-set

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

子命令:

  • image:
    • 更新现有的资源对象的容器镜像。
    • 可使用资源对象包括(不区分大小写):
      • pod (po)
      • replicationcontroller (rc)
      • deployment (deploy)
      • daemonset (ds)
      • job
      • replicaset (rs)
  • resources:
    • 资源对象中的Pod可以指定计算资源需求(CPU-单位m、内存-单位Mi),即使用的最小资源请求(Requests),限制(Limits)的最大资源需求,Pod将保证使用在设置的资源数量范围。
    • 可用资源对象包括(支持大小写):replicationcontroller、deployment、daemonset、job、replicaset。
  • selector:
    • 设置资源的selector(选择器)。如果之前已经存在选择器,则新创建的选择器将覆盖原来的选择器。
  • subject:
    • 更新RoleBinding / ClusterRoleBinding中User、Group 或 ServiceAccount。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# set image
# ------------
# 将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

# set selector
# ------------
# 在创建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 -

# set resources
# ------------
# 将deployment的nginx容器cpu限制为“200m”,将内存设置为“512Mi”
kubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi

# set subject
# ------------
# 更新RoleBinding的user1,user2和group1
kubectl set subject rolebinding admin --user=user1 --user=user2 --group=group1

⭐️ explain

在创建json 和yaml 时,我们可能不知道具体的参数该怎么写。同样 我们可以通过explain这个 命令来查看 每个参数具体的作用与写法。

1
2
3
4
5
6
7
8
9
# Get the documentation of the resource and its fields
kubectl explain pods

# Get the documentation of a specific field of a resource
kubectl explain pods.spec.containers

# 查看StatefulSet的 podManagementPolicy 和 updateStrategy
kubectl explain StatefulSet.spec.podManagementPolicy
kubectl explain StatefulSet.spec.updateStrategy

get

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

1
2
3
4
5
# 列出所有运行的Pod信息。
kubectl get pods

# 列出Pod以及运行Pod节点信息。
kubectl get pods -o wide

edit

  • 使用默认编辑器 编辑服务器上定义的资源。
  • 使用命令行工具获取的任何资源都可以使用edit命令编辑。
  • edit命令会打开使用KUBE_EDITOR,GIT_EDITOR 或者EDITOR环境变量定义的编辑器
  • 可以同时编辑多个资源,但所编辑过的资源只会一次性提交。

一般不怎么用,都是用界面工具

1
2
3
4
5
# 编辑名为'docker-registry'的service:
kubectl edit svc/docker-registry

# 使用替代的编辑器
KUBE_EDITOR="nano" kubectl edit svc/docker-registry

delete

通过配置文件名、stdin、资源名称或label选择器来删除资源。

1
2
3
4
5
6
7
8
9
# 删除名为“baz”和“foo”的Pod和Service。
kubectl delete pod,service baz foo

# 删除 Label name = myLabel的pod和Service。
kubectl delete pods,services -l name=myLabel

# 删除rs,但不删除级联Pod
# 有些资源没有了 ownerReferences 就会被垃圾回收掉
kubectl delete replicaset my-repset --cascade=orphan

部署

⭐️ rollout

对资源进行管理

可用资源包括:

  • deployments
  • daemonsets

子命令

  • history(查看历史版本)
  • pause(暂停资源)
  • resume(恢复暂停资源)
  • status(查看资源状态)
  • undo(回滚版本)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# status
# ------------
# 查看deployment的状态
# - 使用—watch = false 来查看当前状态
# - 需要查看特定修订版本状态 请使用--revision = N 来指定。
kubectl rollout status deployment/nginx

# history
# ------------
# 查看deployment的历史记录
kubectl rollout history deployment/abc

# 查看可用的回滚版本
kubectl ro1lout history deployment demo-deployment

# 查看滚动状态
kubect1 ro1lout status deployments demo-deployment

# 查看daemonset修订版3的详细信息
kubectl rollout history daemonset/abc --revision=3

# undo
# ------------
# 回滚到之前的deployment版本
kubectl rollout undo deployment/abc

# 回滚到daemonset 修订3版本
kubectl rollout undo daemonset/abc --to-revision=3

# pause
# ------------
# 将deployment标记为暂停。#只要deployment在暂停中,使用deployment更新将不会生效。
kubectl rollout pause deployment/nginx

# resume
# ------------
# 恢复已暂停的 deployment
kubectl rollout resume deployment/nginx

scale

  • 扩容或缩容 Deployment、ReplicaSet、Replication Controller或 Job 中Pod数量。
  • scale也可以指定多个前提条件,如:–current-replicas 或 –resource-version ,
  • 进行伸缩比例设置前,系统会先验证前提条件是否成立。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# scale rs
# ------------
# 将名为foo中的pod副本数设置为3。
kubectl scale --replicas=3 rs/foo

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

# scale deployment
# ------------
# 如果当前副本数为2,则将其扩展至3。
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql

# 原本定义3个副本,现在扩容到10个副本
kubect1 scale deployment demo-deployment --replicas 10

# 原本定义3个副本,现在缩容到2个副本
kubect1 scale deployment demo-deployment --replicas 2


# scale rc
# ------------
# 设置多个RC中Pod副本数量。
kubectl scale --replicas=5 rc/foo rc/bar rc/baz

⭐️ autoscale

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

这里有个小前提,要伸缩的pod必须进行资源限制: 限制监控指标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 为Deployment demo-provider-deployment创建一个autoscaler,当Pod的CPU利用率达到50%的时候,RC的replica数量在1到4之间。
# 或者说:
# - 为deployment demo-provider-deployment(微服务POD)创建HPA,其中最小副本数为1,最大副本数为4,保持该deployment的所有Pod的平均CPU使用率不超过50%。
# 在本例中:
# - deployment的pod的resources.request.cpu为250m (250 milli-cores vCPU),
# - 所以HPA将保持所有Pod的平均CPU使用率不超过125m。
kubectl autoscale deployment demo-provider-deployment --cpu-percent=50 --min=1 --max=4

# 使用 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

# 监控 HPA
watch kubectl get hpa

管理

certificate

修改证书资源。

子命令:

  • approve
  • deny
1
2
# Approve CSR 'csr-sqgzp'
kubectl certificate approve csr-sqgzp

cluster-info

查看集群信息,包括 API Server 的地址和端口、DNS 服务的 IP 地址等。

子命令:

  • dump
1
2
# Dump current cluster state to stdout
kubectl cluster-info dump

top

展示资源的cpu和内存使用情况。

子命令:

  • node
  • pod
1
2
3
4
5
6
7
8
9
10
11
# Show metrics for a given node
kubectl top node NODE_NAME

# Show metrics for all pods in the default namespace
kubectl top pod

# Show metrics for all pods in the given namespace
kubectl top pod --namespace=NAMESPACE

# Show metrics for a given pod and its containers
kubectl top pod POD_NAME --containers

⭐️ cordon

  • 将node标记为不可调度。
  • 旧有的pod不会受到影响,仍正常对外提供服务
  • 之后再创建pod,不会被调度到该节点
1
2
# Mark node "foo" as unschedulable
kubectl cordon foo

uncordon

将node标记为可调度。

1
2
# Mark node "foo" as schedulable
kubectl uncordon foo

⭐️ drain

  • 首先,驱逐node上的pod,其他节点重新创建
  • 接着,将节点标记为不可调度。
  • 一般用于维护节点
1
2
3
4
5
# Drain node "foo", even if there are pods not managed by a replication controller, replica set, job, daemon set or stateful set on it
kubectl drain foo --force

# As above, but abort if there are pods not managed by a replication controller, replica set, job, daemon set or stateful set, and use a grace period of 15 minutes
kubectl drain foo --grace-period=900

⭐️ taint

refer doc:

  • https://www.cnblogs.com/panw/p/16343392.html
  • https://kubernetes.io/zh-cn/docs/concepts/scheduling-eviction/taint-and-toleration/

给某个Node节点设置污点,Node被设置上污点之后就和Pod之间存在了一种相斥的关系,可以让Node拒绝Pod的调度执行,甚至将Node已经存在的Pod驱逐出去。

重点:

  • 污点和容忍度(Toleration)相互配合,可以用来避免 Pod 被分配到不合适的节点上。
  • 每个节点上都可以应用一个或多个污点,这表示对于那些不能容忍这些污点的 Pod, 是不会被该节点接受的。
  • 也就是说,哪怕污点是 NoExecute,但是 Pod 设置了相应的容忍度,那么该 Pod 仍然会被调度到该节点上。
  • 详见文档

每个污点的组成:

  • key=value:effect
  • 每个污点有一个 key 和 value 作为污点的标签,其中 value 可以为空,effect 描述污点的作用。

当前 taint effect 支持如下三个选项:

  • NoSchedule:表示k8s将不会将Pod调度到具有该污点的Node上
  • PreferNoSchedule:表示k8s将尽量避免将Pod调度到具有该污点的Node上
  • NoExecute:表示k8s将不会将Pod调度到具有该污点的Node上,同时会将Node上已经存在的Pod驱逐出去
1
2
3
4
5
6
7
8
# 设置污点
kubectl taint nodes k8s-node02 key=value:NoSchedule

#查看污点
kubectl describe node k8s-node02 |grep Taints

#删除污点
kubectl taint nodes k8s-node2 key:NoSchedule-

调试

describe

展示一个或一组资源的详细信息。

1
2
3
4
5
# Describe a pod
kubectl describe pods/nginx

# Describe pods by label name=myLabel
kubectl describe po -l name=myLabel

logs

展示一个 Pod 中容器的日志,或者其他类型资源的日志。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 1)返回仅包含一个容器的pod nginx的日志快照
kubectl logs nginx

# 2)返回pod java中已经停止的容器web-m的日志快照
kubectl logs -p -c java web-m

# 3)持续输出pod java中的容器web-m的日志
kubectl logs -f -c java web-m

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

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

# 6)查看指定pod的日志
kubectl logs <pod_name>
kubectl logs -f <pod_name> #类似tail -f的方式查看(tail -f 实时查看日志文件 tail -f 日志文件log)

# 7)查看指定pod中指定容器的日志
kubectl logs <pod_name> -c <container_name>

exec

在Pod 中指定的容器中执行命令。

  • exec 进入容器后开启一个新的终端,可以在里面操作(常用)
  • 如果使用exit退出,容器也不会停止。
1
2
3
4
5
6
7
8
9
10
11
# Get output from running the 'date' command from pod mypod, using the first container by default
kubectl exec mypod -- date

# Get output from running the 'date' command in ruby-container from pod mypod
kubectl exec mypod -c ruby-container -- date

# Switch to raw terminal mode; sends stdin to 'bash' in ruby-container from pod mypod # and sends stdout/stderr from 'bash' back to the client
kubectl exec mypod -c ruby-container -i -t -- bash -il

# Get output from running 'date' command from the first pod of the deployment mydeployment, using the first container by default
kubectl exec deploy/mydeployment -- date

attach

在Pod 中指定的容器中附加到 stdin,stdout 和 stderr。

  • attach 进入容器正在执行的终端,不会启动新的进程
  • 如果使用exit退出,容器会停止运行!
  • 如果想退出容器但不想容器停止,则按住Ctrl+P+Q退出

refer doc:

  • https://blog.csdn.net/Starrysky_LTL/article/details/121168670
1
2
3
4
5
# Get output from ruby-container from pod mypod
kubectl attach mypod -c ruby-container

# Switch to raw terminal mode; sends stdin to 'bash' in ruby-container from pod mypod # and sends stdout/stderr from 'bash' back to the client
kubectl attach mypod -c ruby-container -i -t

⭐️ port-forward

  • 用于在本地主机和 Kubernetes 集群中的 Pod 之间建立端口转发。
  • 当你运行 kubectl port-forward 命令时,它会将本地主机上的一个端口与 Kubernetes 集群中的一个 Pod 的端口进行绑定。
  • 这样,在本地主机上监听的端口上收到的流量将被转发到 Pod 的端口上,反之亦然。

这个功能在开发和调试应用程序时非常有用。以下是一些 kubectl port-forward的常见用途和好处:

  • 访问远程 Pod 的本地服务:
    • 你可以将 Pod 的端口转发到本地主机,从而能够直接访问 Pod 上运行的服务。
    • 例如,你可以将一个运行在 Kubernetes 集群中的数据库 Pod 的端口转发到本地,以便在本地开发环境中连接和测试数据库。
  • 调试和日志记录:
    • 通过将 Pod 的端口转发到本地,你可以使用本地工具来调试和监视在 Kubernetes 中运行的应用程序。
    • 你可以使用本地的调试器、日志记录工具或其他开发工具来检查应用程序的状态、调试问题或查看日志。
  • 绕过 Kubernetes 服务和负载均衡器:
    • 有时候,你可能想直接访问运行在 Kubernetes 中的应用程序,而不经过 Kubernetes 的服务发现和负载均衡机制。
    • 通过将 Pod 的端口转发到本地,你可以绕过这些机制,直接连接到应用程序。
1
2
3
4
5
6
7
8
# Listen on port 8888 on all addresses, forwarding to 5000 in the pod
kubectl port-forward --address 0.0.0.0 pod/mypod 8888:5000

# Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the deployment
kubectl port-forward deployment/mydeployment 5000 6000

# Listen on port 8443 locally, forwarding to the targetPort of the service's port named "https" in a pod selected by the service
kubectl port-forward service/myservice 8443:https

proxy

  • 是一个用于创建代理服务器的命令,它使你可以通过本地端口访问 Kubernetes 集群内的资源。
  • 这个命令会启动一个 HTTP 代理,监听本地端口,并将请求转发到 Kubernetes API 服务器。
  • 一般用于开发和测试环境

  • 更实用一点的例子:
    • 让外部网络访问K8S service的ClusterIP

refer doc:

  • https://blog.csdn.net/zwqjoy/article/details/87865283
1
2
3
4
# 设置API server接收所有主机的请求:
kubectl proxy --address='0.0.0.0'  --accept-hosts='^*$' --port=8009
# 使用
curl http://[k8s-master]:8009/api/v1/namespaces/[namespace-name]/services/[service-name]/proxy

⭐️ cp

  • 将本地文件/目录拷贝到 Pod 中。
  • 将Pod 中的文件/目录拷贝到本地。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir

# Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>

# Copy /tmp/foo from a remote pod to /tmp/bar locally
kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar


# 装逼用法
# -----------
# Copy /tmp/foo from a remote pod to /tmp/bar locally
kubectl exec -n <some-namespace> <some-pod> -- tar cf - /tmp/foo | tar xf - -C /tmp/bar

#  Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace
tar cf - /tmp/foo | kubectl exec -i -n <some-namespace> <some-pod> -- tar xf - -C /tmp/bar

auth

refer doc:

  • https://www.cjavapy.com/article/2812/

子命令:

  • can-i: 查看权限
  • reconcile: 根据roles.yaml文件,重新计算、应用权限
    • roles.yaml文件,参考Role, ClusterRole
1
2
3
4
5
6
7
8
# 检查我是否可以在任何命名空间中创建pod
kubectl auth can-i create pods --all-namespaces

# 列出命名空间"cjavapy"中所有允许的操作
kubectl auth can-i --list --namespace=cjavapy

# 协调文件中的RBAC资源
kubectl auth reconcile -f my-rbac-rules.yaml

⭐️ debug

refer doc:

  • https://zhuanlan.zhihu.com/p/575061917

原理:

  • 我们知道,容器本质上是带有 cgroup 资源限制和 namespace 隔离的一组进程。
  • 因此,我们只要启动一个进程,并且让这个进程加入到目标容器的各种 namespace 中,这个进程就能 “进入容器内部”(注意引号),与容器中的进程 “看到” 相同的根文件系统、虚拟网卡、进程空间了
  • 这也正是 docker exec 和 kubectl exec 等命令的运行方式。

  • 现在的状况是,我们不仅要 “进入容器内部”,还希望带一套工具集进去帮忙排查问题。
  • 那么,想要高效管理一套工具集,又要可以跨平台,最好的办法就是把工具本身都打包在一个容器镜像当中。
  • 接下来,我们只需要通过这个 “工具镜像” 启动容器,
  • 再指定这个容器加入目标容器的的各种 namespace,自然就实现了 “携带一套工具集进入容器内部”。

  • 建议镜像:nicolaka/netshoot
  • https://zhuanlan.zhihu.com/p/95664681

  • debug 容器也叫做 临时容器。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 在名为 mypod 的 Pod 中创建一个交互式调试会话并立即挂接到此会话
kubectl debug mypod -it --image=busybox

# 为文件 pod.yaml 中的 Pod 创建一个交互式调试会话并立即挂接到此会话
# (需要在集群中启用 EphemeralContainers 特性)
kubectl debug -f pod.yaml -it --image=busybox

# 使用特定的自动调试镜像创建一个名为 debugger 的调试容器
kubectl debug --image=myproj/debug-tools -c debugger mypod

# 创建 mypod 的副本,添加调试容器并挂接到此容器
kubectl debug mypod -it --image=busybox --copy-to=my-debugger

# 创建 mypod 的副本,更改 mycontainer 的命令
kubectl debug mypod -it --copy-to=my-debugger --container=mycontainer -- sh

# 创建 mypod 的副本,将所有容器镜像更改为 busybox
kubectl debug mypod --copy-to=my-debugger --set-image=*=busybox

# 创建 mypod 的副本,添加调试容器并更改容器镜像
kubectl debug mypod -it --copy-to=my-debugger --image=debian --set-image=app=app:debug,sidecar=sidecar:debug

# 在节点上创建一个交互式调试会话并立即挂接到此会话
# 容器将在主机命名空间中运行,主机的文件系统将被挂载到 /host
kubectl debug node/mynode -it --image=busybox

events

  • 显示事件。
  • 打印有关事件的最重要信息的表格。您可以请求命名空间的事件,所有命名空间的事件,或仅筛选与指定资源相关的事件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 列举 default 命名空间中近期的事件
kubectl events
  
# 列举所有命名空间中近期的事件
kubectl events --all-namespaces
  
# 列举指定 Pod 的近期事件,然后等待更多事件,并在出现新事件时列举出来
kubectl events --for pod/web-pod-13je7 --watch
  
# 以 YAML 格式列举近期的事件
kubectl events -oyaml
  
# 仅列举类别为 “Warning” 或 “Normal” 的近期事件
kubectl events --types=Warning,Normal

高级

diff

  • 对比当前在线配置与通过文件名或标准输入所指定的配置之间的差异,并显示如果应用配置后将会如何变化。
  • 输出始终是 YAML。
1
2
3
4
5
# 对比 pod.json 中包含的资源
kubectl diff -f pod.json
  
# 对比从标准输入读取到的文件
cat service.yaml | kubectl diff -f -

apply

  • 对现有对象进行增量更改,根据yaml文件里面列出来的内容,升级现有的资源对象
  • yaml文件的内容可以只写需要升级的属性
  • 若要使用 apply 命令,最初创建资源时应始终使用 apply 或 create –save-config。

子命令:

  • edit-last-applied: 使用默认编辑器编辑资源的最新的 last-applied-configuration 注解。
  • set-last-applied: 设置 last-applied-configuration 注解使之与某文件内容相匹配。
    • 这会导致 last-applied-configuration 被更新,就像运行了 kubectl apply -f 一样, 但是不会更新对象的任何其他部分。
  • view-last-applied: 根据所给类别/名称或文件来查看最新的 last-applied-configuration 注解。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 将 pod.json 中的配置应用到 Pod
kubectl apply -f ./pod.json
  
# 应用来自包含 kustomization.yaml 的目录(即 dir/kustomization.yaml)中的资源
kubectl apply -k dir/
  
# 应用所有以 ".json" 结尾的文件中的配置
kubectl apply -f '*.json'

# 在 YAML 中按类型/名称编辑 last-applied-configuration 注解
kubectl apply edit-last-applied deployment/nginx

# 设置资源的 last-applied-configuration,使之与某文件内容相同
kubectl apply set-last-applied -f deploy.yaml
  
# 针对目录中的每一个配置文件执行 set-last-applied 操作
kubectl apply set-last-applied -f path/

# 根据所给类别/名称以 YAML 格式查看 last-applied-configuration 注解
kubectl apply view-last-applied deployment/nginx

patch

使用策略合并补丁、JSON 合并补丁或 JSON 补丁来更新某资源的字段。

1
2
3
4
5
# 使用策略合并补丁部分更新节点,指定补丁为 JSON 格式
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
  
# 使用策略合并补丁部分更新以在 "node.json" 中所指定类别和名称标识的节点
kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}'

replace

按文件名或标准输入来替换某资源。

1
2
3
4
5
6
7
8
# 使用 pod.json 中的数据替换 Pod
kubectl replace -f ./pod.json
  
# 将单容器 Pod 的镜像版本(标签)更新为 v4
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
  
# 强制替换、删除,然后重新创建资源
kubectl replace --force -f ./pod.json

wait

  • 实验特性
  • 等待一个或多个资源到达特定状态。
  • 此命令接受多个资源作为输入,并等待直到在每个给定资源的状态字段中看到所指定的状况。
1
2
3
4
5
6
7
8
9
# 等待 Pod "busybox1" 包含 "Ready" 类型的状况值
kubectl wait --for=condition=Ready pod/busybox1

# 等待 Pod "busybox1" 的状态阶段包含 "Running"
kubectl wait --for=jsonpath='{.status.phase}'=Running pod/busybox1

# 发出 "delete" 命令后,等待 Pod "busybox1" 被删除,超时时间为 60 秒
kubectl delete pod/busybox1
kubectl wait --for=delete pod/busybox1 --timeout=60s

kustomize

refer doc:

  • https://kubernetes.io/zh-cn/docs/tasks/manage-kubernetes-objects/kustomization/

  • Kustomize 是一个独立的工具,用来通过 kustomization 文件 定制 Kubernetes 对象。

暂时跳过

设置

label

更新资源上的标签。

1
2
3
4
5
# 使用标签 'unhealthy' 和值 'true' 更新 Pod 'foo'
kubectl label pods foo unhealthy=true

# 仅在资源版本为 1 且未更改时更新 Pod 'foo'
kubectl label pods foo status=unhealthy --resource-version=1

annotate

更新一个或多个资源上的注解。

1
2
3
4
5
6
# 使用注解 'description' 和值 'my frontend' 更新 Pod 'foo'
# 如果同一注解被设置多次,则只使用最后一个值
kubectl annotate pods foo description='my frontend'

# 更新命名空间中的所有 Pod
kubectl annotate pods --all description='my frontend running nginx'

completion

  • 用于 shell 自动补全
  • 输出指定 shell(bash、zsh、fish 或 powershell)的 shell 补全代码。

其他

api-resources

打印服务器支持的 API 资源。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 打印服务器支持的 API 资源
kubectl api-resources

# 打印支持的 API 资源,但包含更多信息
kubectl api-resources -o wide

# 按列排序打印支持的 API 资源
kubectl api-resources --sort-by=name

# 打印支持的命名空间资源
kubectl api-resources --namespaced=true

# 打印支持的非命名空间资源
kubectl api-resources --namespaced=false

# 打印特定 APIGroup 支持的 API 资源
kubectl api-resources --api-group=rbac.authorization.k8s.io

api-versions

以 “group/version” 的形式打印服务器支持的 API 版本。

1
2
# Print the supported API versions
kubectl api-versions

config

使用 “kubectl config set current-context my-context” 等子命令修改 kubeconfig 文件。

暂时跳过

plugin

  • 提供与插件交互的实用程序。
  • 插件提供主要命令行发布版本所不具备的扩展功能
1
2
3
4
5
6
7
8
9
10
11
12
wget https://github.com/kubernetes-sigs/krew/releases/download/v0.4.4/krew-linux_amd64.tar.gz
wget https://github.com/kubernetes-sigs/krew/releases/download/v0.4.4/krew.yaml
tar -xf krew-linux_amd64.tar.gz 
./krew-linux_amd64 install     --manifest=krew.yaml --archive=krew-linux_amd64.tar.gz
cat >> ~/.bashrc << EOF
export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"
EOF

kubectl krew update

# 查看安装成功
kubectl krew search whoami

kubectl 插件:

  • krew: krew是一个Kubernetes的包管理工具,它的功能就是提供简单的方法下载、检索、管理其他插件,类似操作系统的apt、yum、brew等工具,其命名也似乎模仿的brew工具。
  • iexec: exec命令的功能增强版本,可以通过Pod模糊查询然后交互式选择
  • access-matrix: 显示服务器资源的 RBAC 访问矩阵。
  • ca-cert: 打印当前集群的 PEM CA 证书
  • cert-manager: 这个不用多介绍了吧?大名鼎鼎的 cert-manager,用来管理集群内的证书资源。
  • cost: 查看集群成本信息。
  • df-pv: 通过读取的summay API获取pv的使用量
  • resource-capacity: 查看Node节点的CPU和内存使用情况:
  • view-allocations: 如果要查看更详细,细粒度到每个Pod,则可以使用view-allocations插件:
  • images: 显示集群中使用的容器镜像。
  • starboard: 也是一个安全扫描工具。可以生成一份安全报告
  • tree: 通过对 Kubernetes 对象的 ownersReferences来探索它们之间的所有权关系。

refer doc:

version

打印当前上下文的客户端和服务器版本信息。

资源名称简写大全

资源名称简写
componentstatusescs
configmapscm
endpointsep
eventsev
limitrangeslimits
namespacesns
nodesno
persistentvolumeclaimspvc
persistentvolumespv
podspo
replicationcontrollersrc
resourcequotasquota
serviceaccountssa
servicessvc
customresourcedefinitionscrd,crds
daemonsetsds
deploymentsdeploy
replicasetsrs
statefulsetssts
horizontalpodautoscalershpa
cronjobscj
certificatesigningrequestscsr
eventsev
ingressesing
ipaddressesip
networkpoliciesnetpol
poddisruptionbudgetspdb
priorityclassespc
storageclassessc
volumeattributesclassesvac
This post is licensed under CC BY 4.0 by the author.