深色模式
kubectl 常用命令速查
摘要:本文不罗列全部参数,只整理运维每天都在用的 kubectl 操作:查看资源、看事件、查日志、进容器、批量筛选与输出格式化,以及多集群上下文切换。命令可直接复制。
适用环境
- 任意可用 K8s 集群 + 配好 kubeconfig 的
kubectl kubectl与集群版本差不超过一个小版本
操作步骤
一、环境自检
bash
kubectl version --short 2>/dev/null || kubectl version
kubectl cluster-info
kubectl api-resources # 列出所有资源类型及缩写
kubectl config get-contexts # 看有哪些集群
kubectl config use-context <上下文名>1
2
3
4
5
2
3
4
5
二、查看资源(get)
bash
kubectl get nodes
kubectl get pods -A # 所有命名空间
kubectl get pod -n default -o wide # 带节点和 IP
kubectl get pod -w # 持续观察变化
kubectl get deploy,svc,ing # 多类型一起看
kubectl get pod -l app=web # 按标签筛选
kubectl get pod --field-selector status.phase=Running
kubectl get pod --sort-by=.metadata.creationTimestamp1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
三、查看详情(describe)—— 排障第一命令
bash
kubectl describe pod <pod名>
kubectl describe node <节点名>
kubectl describe svc <服务名>1
2
3
2
3
describe 输出的 Events 段是定位问题的关键,会直接告诉你镜像拉取失败、调度失败、探针失败等原因。
四、查看日志(logs)
bash
kubectl logs <pod名>
kubectl logs <pod名> -c <容器名> # 多容器 Pod 必须指定
kubectl logs -f <pod名> --tail=100 # 实时跟踪
kubectl logs <pod名> --previous # 看崩溃前一次容器的日志
kubectl logs -l app=web --all-containers # 按标签批量看1
2
3
4
5
2
3
4
5
建议
容器反复重启时,kubectl logs --previous 是唯一能看到上次崩溃日志的方式,务必记住。
五、进入容器(exec)
bash
kubectl exec -it <pod名> -- sh
kubectl exec -it <pod名> -c <容器名> -- bash
kubectl exec <pod名> -- env
kubectl exec <pod名> -- cat /etc/resolv.conf1
2
3
4
2
3
4
注意
生产环境不要靠 exec 改文件来修复问题——Pod 重建后改动全部丢失。它只应用于临时诊断。
六、输出格式化与批量操作
bash
kubectl get pod -o yaml
kubectl get pod -o json
kubectl get pod -o name
kubectl get pod -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,IP:.status.podIP
kubectl get pod -o jsonpath='{.items[*].metadata.name}'
kubectl get deploy web -o jsonpath='{.spec.replicas}'1
2
3
4
5
6
2
3
4
5
6
批量删除(危险):
bash
kubectl delete pod -l app=web
kubectl delete pod --field-selector status.phase=Failed
kubectl delete pod <pod名> --force --grace-period=01
2
3
2
3
危险
--force --grace-period=0 会跳过优雅退出直接杀进程,对有状态服务(数据库)可能造成数据损坏。仅在前置 Pod 卡在 Terminating 且确认无写入时使用。
七、临时调试容器
bash
kubectl debug -it <pod名> --image=busybox --target=<容器名>
kubectl run net-test --rm -it --image=busybox --restart=Never -- sh1
2
2
八、编辑与生效
bash
kubectl edit deploy web
kubectl scale deploy web --replicas=5
kubectl apply -f app.yaml
kubectl delete -f app.yaml
kubectl diff -f app.yaml # 先看会改什么1
2
3
4
5
2
3
4
5
验证
- [ ]
kubectl get pods -A无异常状态 Pod - [ ] 能用
describe找到一个 Pod 的事件信息 - [ ] 能用 jsonpath 取出指定字段
常见坑
Error from server (NotFound):当前命名空间不对,加-n <命名空间>或用kubectl config set-context --current --namespace=xxx。- 多容器 Pod 报错
a container name must be specified:必须在logs/exec后加-c <容器名>。 kubectl logs空输出:容器可能刚开始或已重启,加--previous或--timestamps确认时间点。- kubectl 与集群版本差太多报兼容错误:
kubectl version显示的 client 与 server 版本差不应超过一个小版本。 - 命令补全没配:执行
kubectl completion bash > /etc/bash_completion.d/kubectl并重新登录,效率提升明显。