kubectl 命令梳理
Kubctl 命令是操作 kubernetes 集群的最直接的途径,下面对相关命令进行简介:
语法
| $ kubectl [command] [TYPE] [NAME] [flags] |
| |
| command:子命令 |
| TYPE:资源类型 |
| NAME:资源名称 |
| flags:命令参数 |
| |
| 命令帮助 |
| kubectl命令的帮助很详细,kubectl -h会列出所有的子命令,在任何子命令后跟 -h,都会输出详细的帮助以及用例,遇到问题可以随时查看帮助。 |
| |
| 资源对象 |
| kubectl大部分子命令后都可以指定要操作的资源对象,可以用kubectl api-resources命令参考 |
| |
| 全局参数 |
| kubectl options命令可以列出可以全局使用的命令参数,比较重要的有: |
| |
| --cluster='': 指定命令操作对象的集群 |
| --context='': 指定命令操作对象的上下文 |
| -n, --namespace='': 指定命令操作对象的Namespace |
| |
| 资源字段 |
| kubectl explain命令可以输出资源对应的属性字段及定义,在定义资源配置文件时候非常有用。 |
Kubectl 自动补全
| k8s 命令自动补全 |
| $ yum install -y bash-completion |
| $ source /usr/share/bash-completion/bash_completion |
| $ source <(kubectl completion bash) |
| $ echo "source <(kubectl completion bash)" >> ~/.bashrc |
Kubectl 上下文和配置
| 设置 kubectl 命令交互的 kubernetes 集群并修改配置信息。参阅 使用 kubeconfig 文件进行跨集群验证 获取关于配置文件的详细信息。 |
| |
| $ kubectl config view |
| |
| |
| |
| $ KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config view |
| |
| |
| $ kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}' |
| |
| $ kubectl config current-context |
| $ kubectl config use-context my-cluster-name |
| |
| |
| $ 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 |
创建对象
Kubernetes 的清单文件可以使用 json 或 yaml 格式定义。可以以 .yaml、.yml、或者 .json 为扩展名。
| $ kubectl create -f ./my-manifest.yaml |
| $ kubectl create -f ./my1.yaml -f ./my2.yaml |
| $ kubectl create -f ./dir |
| $ kubectl create -f https://git.io/vPieo |
| $ kubectl run nginx --image=nginx |
| $ kubectl explain pods,svc |
| |
| |
| $ cat <<EOF | kubectl create -f - |
| apiVersion: v1 |
| kind: Pod |
| ... |
| - "1000000" |
| --- |
| apiVersion: v1 |
| kind: Pod |
| ... |
| - sleep |
| - "1000" |
| EOF |
| |
| |
| $ cat <<EOF | kubectl create -f - |
| apiVersion: v1 |
| .... |
| EOF |
删除容器组
| 1.强制删除特定pods |
| |
| 2.删除集群失败的pods |
| |
| 3.强制删除Terminating状态的pods |
| |
| |
显示和查找资源
| |
| $ kubectl get services |
| $ kubectl get pods --all-namespaces |
| $ kubectl get pods -o wide |
| $ kubectl get deployment my-dep |
| $ kubectl get pods --include-uninitialized |
| |
| |
| $ kubectl describe nodes my-node |
| $ kubectl describe pods my-pod |
| |
| $ kubectl get services --sort-by=.metadata.name |
| |
| |
| $ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' |
| |
| |
| $ kubectl get pods --selector=app=cassandra rc -o \ |
| jsonpath='{.items[*].metadata.labels.version}' |
| |
| |
| $ kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}' |
| |
| |
| |
| $ sel=${$(kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?} |
| $ echo $(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name}) |
| |
| |
| $ JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \ |
| && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True" |
| |
| |
| $ kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq |
更新资源
| $ kubectl rolling-update frontend-v1 -f frontend-v2.json |
| $ 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 |
| $ cat pod.json | kubectl replace -f - |
| |
| |
| $ kubectl replace --force -f ./pod.json |
| |
| |
| $ kubectl expose rc nginx --port=80 --target-port=8000 |
| |
| |
| $ kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f - |
| |
| $ kubectl label pods my-pod new-label=awesome |
| $ kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq |
| $ kubectl autoscale deployment foo --min=2 --max=10 |
修补资源
使用策略合并补丁并修补资源。
| $ kubectl patch node k8s-node-1 -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 patch deployment valid-deployment --type json -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]' |
编辑资源
在编辑器中编辑任何 API 资源。
| $ kubectl edit svc/docker-registry |
| $ KUBE_EDITOR="nano" kubectl edit svc/docker-registry |
Scale 资源
| $ kubectl scale --replicas=3 rs/foo |
| $ kubectl scale --replicas=3 -f foo.yaml |
| $ kubectl scale --current-replicas=2 --replicas=3 deployment/mysql |
| $ kubectl scale --replicas=5 rc/foo rc/bar rc/baz |
删除资源
| $ kubectl delete -f ./pod.json |
| $ kubectl delete pod,service baz foo |
| $ kubectl delete pods,services -l name=myLabel |
| $ kubectl delete pods,services -l name=myLabel --include-uninitialized |
| $ kubectl -n my-ns delete po,svc --all |
与运行中的 Pod 交互
| $ kubectl logs my-pod |
| $ kubectl logs my-pod -c my-container |
| $ kubectl logs -f my-pod |
| $ kubectl logs -f my-pod -c my-container |
| $ kubectl run -i --tty busybox --image=busybox -- sh |
| $ kubectl attach my-pod -i |
| $ kubectl port-forward my-pod 5000:6000 |
| $ kubectl exec my-pod -- ls / |
| $ kubectl exec my-pod -c my-container -- ls / |
| $ kubectl top pod POD_NAME --containers |
与节点和集群交互
| $ kubectl cordon my-node |
| $ kubectl drain my-node |
| $ kubectl uncordon my-node |
| $ kubectl top node my-node |
| $ kubectl cluster-info |
| $ kubectl cluster-info dump |
| $ kubectl cluster-info dump --output-directory=/path/to/cluster-state |
| |
| |
| $ kubectl taint nodes foo dedicated=special-user:NoSchedule |
资源类型
下表列出的是 kubernetes 中所有支持的类型和缩写的别名。
| 资源类型 缩写别名 指定 Namespaced |
| componentstatuses cs FALSE |
| configmaps cm TRUE |
| endpoints ep TRUE |
| limitranges limits TRUE |
| namespaces ns FALSE |
| nodes no FALSE |
| persistentvolumeclaims pvc TRUE |
| persistentvolumes pv FALSE |
| pods po TRUE |
| replicationcontrollers rc TRUE |
| resourcequotas quota TRUE |
| serviceaccounts sa TRUE |
| services svc TRUE |
| customresourcedefinitions crd, crds FALSE |
| daemonsets ds TRUE |
| deployments deploy TRUE |
| replicasets rs TRUE |
| statefulsets sts TRUE |
| horizontalpodautoscalers hpa TRUE |
| cronjobs cj TRUE |
| certificatesigningrequests csr FALSE |
| events ev TRUE |
| ingresses ing TRUE |
| networkpolicies netpol TRUE |
| poddisruptionbudgets pdb TRUE |
| podsecuritypolicies psp FALSE |
| priorityclasses pc FALSE |
| storageclasses sc FALSE |
格式化输出
要以特定的格式向终端窗口输出详细信息,可以在 kubectl 命令中添加 -o 或者 -output 标志。
| 输出格式 描述 |
| -o=custom-columns=<spec> 使用逗号分隔的自定义列列表打印表格 |
| -o=custom-columns-file=<filename> 使用 文件中的自定义列模板打印表格 |
| -o=json 输出 JSON 格式的 API 对象 |
| -o=jsonpath=<template> 打印 jsonpath 表达式中定义的字段 |
| -o=jsonpath-file=<filename> 打印由 文件中的 jsonpath 表达式定义的字段 |
| -o=name 仅打印资源名称 |
| -o=wide 以纯文本格式输出任何附加信息,对于 Pod ,包含节点名称 |
| -o=yaml 输出 YAML 格式的 API 对象 |
根据overlay2目录名找容器
| $ docker ps -q | xargs docker inspect --format '{{.State.Pid}}, {{.Id}}, {{.Name}}, {{.GraphDriver.Data.WorkDir}}' |
调试coredns
| $ kubectl run -it --rm --restart=Never --image=infoblox/dnstools:latest dnstools |
查看各节点资源使用情况
| $ kubectl get nodes --no-headers | awk '{print $1}' | xargs -I {} sh -c "echo {} ; kubectl describe node {} | grep Allocated -A 5 | grep -ve Event -ve Allocated -ve percent -ve --;" |
查看资源总情况
| $ kubectl get no -o=custom-columns="NODE:.metadata.name,ALLOCATABLE CPU:.status.allocatable.cpu,ALLOCATABLE MEMORY:.status.allocatable.memory" |
| # 获取节点列表及其内存容量 |
| $ kubectl get no -o json | \ |
| jq -r '.items | sort_by(.status.capacity.memory)[]|[.metadata.name,.status.capacity.memory]| @tsv' |
查看CPU分配情况
| $ kubectl get nodes --no-headers | awk '{print $1}' | xargs -I {} sh -c 'echo -n "{}\t" ; kubectl describe node {} | grep Allocated -A 5 | grep -ve Event -ve Allocated -ve percent -ve -- | grep cpu | awk '\''{print $2$3}'\'';' |
查看内存分配情况
| $ kubectl get nodes --no-headers | awk '{print $1}' | xargs -I {} sh -c 'echo -n "{}\t" ; kubectl describe node {} | grep Allocated -A 5 | grep -ve Event -ve Allocated -ve percent -ve -- | grep memory | awk '\''{print $2$3}'\'';' |
线程数统计
| $ printf " NUM PID\t\tCOMMAND\n" && ps -eLf | awk '{$1=null;$3=null;$4=null;$5=null;$6=null;$7=null;$8=null;$9=null;print}' | sort |uniq -c |sort -rn | head -10 |
配置默认storageclass
| $ kubectl patch storageclass <your-class-name> -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}' |
查看容器名
| $ yum install jq |
| $ kubectl get pod calibre-web-76b9bf4d8b-2kc5j -o json | jq -j ".spec.containers[].name" |
查找非 running 状态的 Pod
| $ kubectl get pods -A --field-selector=status.phase!=Running | grep -v Complete |
获取每个节点的Pod数量
| $ kubectl get po -o json --all-namespaces | \ |
| jq '.items | group_by(.spec.nodeName) | map({"nodeName": .[0].spec.nodeName, "count": length}) | sort_by(.count)' |
批量删除所有命名空间下某一个状态的所有pod
| $ kubectl get pods --all-namespaces |grep Terminating | awk 'NR>1 {print $1 ,$2}' | xargs -l -t kubectl delete pod --force --grace-period=0 -n $1 $2 |
| $ kubectl get pods --all-namespaces |grep Evicted | awk 'NR>1 {print $1 ,$2}' | xargs -l -t kubectl delete pod --force --grace-period=0 -n $1 $2 |
使用kubectl-debug对某一个pod进行转包分析
| $ kubectl-debug pod-name-xxxx -n xxxx --agentless --port-forward |
| $ tcpdump -n -vvv -w /tmp/xxx.pcap |
Kubectl 详细输出和调试
使用 -v 或 --v 标志跟着一个整数来指定日志级别。
| 详细等级 描述 |
| --v=0 总是对操作人员可见。 |
| --v=1 合理的默认日志级别,如果您不需要详细输出。 |
| --v=2 可能与系统的重大变化相关的,有关稳定状态的信息和重要的日志信息。这是对大多数系统推荐的日志级别。 |
| --v=3 有关更改的扩展信息。 |
| --v=4 调试级别详细输出。 |
| --v=6 显示请求的资源。 |
| --v=7 显示HTTP请求的header。 |
| --v=8 显示HTTP请求的内容。 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?