「kubectl」- 常用操作

创建资源(增)

通过文件创建

从标准输入读取 YAML 定义:

kubectl apply -f <<EOF
kind: xxx
...
EOF

// 应用目录的多个 YAML 文件
// 通过 --recursive 进行递归应用
kubectl apply -f <directory>
kubectl apply -f <directory> --recursive

删除资源(删)

删除命名空间:kubectl delete namesapce

根据标签删除特定的资源:kubectl delete svc,deploy -l app=niceone

强行删除 PODS:kubectl delete pods pod-name –grace-period=0 –force

删除指定命名空间内的 PODS:kubectl delete pods –all –namespace test

!!!不要直接删除被监控的对象,例如由部署控制的 POD 等等。应该先关闭监控进程,或者用特定的操作删除被管理的资源。例如,可以将一个部署缩小到零个副本,然后就可以有效的删除它所监控的 POD 了!!!

!!!级联删除和直接删除!!!当删除一个自定义的资源定义时,其所有的依赖对象也会被删除。参考「Garbage Collection」手册;

删除 Pod 对象

使用 kubectl delete pods xxx 删除对应的 pod,提示删除成功,但是立马又回生成一个。为何?
how to delete/remove calico cni from my kubernetes cluster
Command to delete all pods in all kubernetes namespaces – Stack Overflow

kubectl delete pods "pod name"

# 强制删除命名空间内的全部 Pod 实例
kubectl delete --all pods --namespace=ingress-nginx --force --grace-period 0

资源管理

参考 06.Kubernetes API Objects 笔记,获取使用 kubectl 管理 Pod Service Ingress Deployment 等等资源的方法(详见子章节)

删除资源定义:

kubectl delete -f foo.yaml

修改资源(改)

脚本化 | kubectl patch

Get YAML for deployed Kubernetes services? – Stack Overflow

如果是为了修改,则可以考虑使用 kubectl patch xxx –dry-run=client –type merge -o yaml | kubectl replace -f

交互式 | kubectl edit

使用 kubectl edit 编辑资源:

# kubectl run nginx --image=nginx
# kubectl edit deployment/nginx

然后会在编辑器内打开。修改信息后,系统会提示:deployment “nginx” edited

补充说明:
并不是所有的变更都互触发部署
可以设置 EDITOR 环境变量来指定编辑器,例如 EDITOR=emacs 来使用 Emacs 编辑器
部分触发器由快捷键:例如修改部署的镜像版本,可以使用 kubectl set image,该命令可以更新已有容器的镜像资源(对部署,副本集,副本控制器,服务进程集,简单的 POD 都有效)

kubectl patch

Kubernetes – kubectl patch
Stack Overflow/Is it possible to add multiple values to an array within a sinlge patch execution

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

# 添加元素到指定路径
kubectl patch deployment cert-manager -n cert-manager --type "json" -p '[
{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--default-issuer-name=letsencrypt-prod"},
{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--default-issuer-kind=ClusterIssuer"},
{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--default-issuer-group=cert-manager.io"}]'

kubectl rollout

Kubernetes/Deployments

# 查看历史版本
kubectl rollout history deployment sise

# 执行撤回操作
kubetl rollout undo deployment sise --to-revision=2

# 查看撤回结果
kubectl rollout status deployment sise

查询资源(查)

查看命名空间:kubectl get namespace

查看 Pod 对象:

# 查看 Namespace 所有的 Pod 实例:
kubectl get pods
kubectl get pods -n "namespace"

# 通过 Label 过滤 Pod 对象
kubectl get pods -l app=web

查看所有的服务和部署:kubectl get services,deployments

查看特定的部署:kubectl get deployment dep-name

查看所有资源:kubectl get all

很多资源都有简写:configmap cm, daemonsets ds, deployments deploy, endpoints ep, events ev, horizontalpodautoscalers hpa, ingresses ing, namespaces ns, nodes no, persistentvolumeclaims pvc, persistentvolumes pv, pods po, replicasets rs, replactioncontrollers rc, resourcequotas quota, serviceaccounts sa, services svc

watch

观察资源的变化:kubectl get pods –watch # 该命令类似于 TOP 命令,但是在刷新屏幕时,有时不太可靠

还可以使用:watch kubectl get pods

explain

命令 kubectl explain 从 Swagger/OpenAPI 定义中摘取由 API 服务器提供的资源和字段描述;

获取字段的信息:

# kubectl explain service
# kubectl explain service.metadata
# kubectl explain service.metadata.namespace

managedFields

itaysk/kubectl-neat: Clean up Kubernetes yaml and json output to make it readable
kubectl get -o yaml: is it possible to hide metadata.managedFields? – Stack Overflow

# 查看部署资源:
kubectl get deployments.apps cert-manager -o yaml

# 关于多余字段:
# managedFields:旧版本将显示 managedFields 字段;Kubectl 1.21 将隐藏 managedFields 字段
# 通过 neat 插件开移除无关字段:kubectl get pod mypod -o yaml | kubectl neat

导出 YAML 资源

kubectl get deploy deploymentname -o yaml

常用命令

Kubectl Apply – All Files in Directory – ShellHacks

默认 namespace 配置:

# 修改特定 Context 的默认命名空间
kubectl config set-context "foo-internal" --namespace=ggckad-s2

# 修改当前 Context 的默认命名空间
kubectl config set-context --current --namespace=namepsace_name

端口转发(kubectl port-forward)

端口转发通常用于测试或者调试,不会在生产中使用,因此这里仅简单介绍,能够满足需求即可;

// 转发 kubernetes-dashboard Service 的 443 端口
// 但是,默认监听 127.0.0.1 地址

# kubectl port-forward -n kubernetes-dashboard service/kubernetes-dashboard 30001:443
Forwarding from 127.0.0.1:30001 -> 8443
Forwarding from [::1]:30001 -> 8443

// 转发 kubernetes-dashboard Service 的 443 端口
// 并使其监听 0.0.0.0 地址

# kubectl port-forward -n kubernetes-dashboard service/kubernetes-dashboard --address 0.0.0.0 30001:443
Forwarding from 0.0.0.0:30001 -> 8443

// 如果需要直接转发 Pod 的端口

# kubectl port-forward pods/mongo-75f59d57f4-4nd6q 28015:27017

复制文件(kubectl cp)

azure aks – How to copy files from kubernetes Pods to local system

kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar                        # 复制本地文件到容器

kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar                        # 复制容器文件到本地

参考文献

Optional kubectl configurations/Introduction
Get YAML for deployed Kubernetes services?
kubectl Port-Forward – Kubernetes Port Forwarding Guide
How to change default Namespace in Kubernetes | Edureka Community
kubectl Cheat Sheet | Kubernetes

kubectl apply vs. kubectl create

Kubectl Apply vs. Kubectl Create – What’s the Difference?

Imperative management means giving a series of instructions or steps to reach the goal. We specify what and how we should reach the goal.

This is where we tell K8S what to create, replace, delete, etc., using the API. Objects are created and managed using the kubectl command on the command line interface (CLI).

kubectl create — This is an imperative command.

简而言之,其更倾向于操作过程。

Declarative management is where we specify the required outcome, not the individual steps needed to achieve that outcome.

For each kind of resource specified in our YAML configuration files, a dedicated controller checks what we currently have and tries to converge it with what we want.

kubectl apply — This is a declarative command.

简而言之,其更倾向于期望结果。

kubectl patch | 修改 YAML 内容

templates – How to set dynamic values with Kubernetes yaml file – Stack Overflow
kubernetes – How can I edit a Deployment without modify the file manually? – Stack Overflow

envsubst | 需要预先在 YAML中定义 ${XXX} 变量

kubectl patch deployment myapp-deployment -p \
  '{"spec":{"template":{"spec":{"containers":[{"name":"myapp","image":"172.20.34.206:5000/myapp:img:3.0"}]}}}}'

kubectl replace | 替换对象

https://kubernetes.io/docs/reference/kubectl/generated/kubectl_replace/