摘要:kubectl 是操作 Kubernetes 集群的核心命令行工具。本文按使用场景系统整理 kubectl 常用命令,覆盖集群管理、资源查询、应用部署、日志排查、网络调试、性能分析等方面,可作为日常运维的快速参考手册。
一、基础配置
1.1 集群连接与上下文切换
# 查看当前 kubeconfig 配置
kubectl config view
# 查看当前使用的上下文
kubectl config current-context
# 列出所有上下文
kubectl config get-contexts
# 切换到指定上下文(多集群管理时常用)
kubectl config use-context <context-name>
# 设置默认命名空间(避免每次输入 -n)
kubectl config set-context --current --namespace=<namespace>
# 验证集群连接
kubectl cluster-info
# 查看 API Server 和 CoreDNS 地址
kubectl cluster-info dump | head -20
1.2 kubectl 自动补全
# Bash 自动补全
source <(kubectl completion bash)
echo 'source <(kubectl completion bash)' >> ~/.bashrc
# Zsh 自动补全
source <(kubectl completion zsh)
echo 'source <(kubectl completion zsh)' >> ~/.zshrc
# 设置别名(推荐)
alias k=kubectl
complete -o default -F __start_kubectl k
1.3 输出格式
# 默认表格输出
kubectl get pods
# 宽格式(含 IP、Node 等额外列)
kubectl get pods -o wide
# YAML 输出(查看完整资源定义)
kubectl get pod <pod-name> -o yaml
# JSON 输出
kubectl get pod <pod-name> -o json
# 自定义列输出
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName
# JSONPath 提取特定字段
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# 只输出资源名称
kubectl get pods -o name
二、集群与节点管理
2.1 集群信息
# 集群基本信息
kubectl cluster-info
# 查看 API 版本
kubectl api-versions
# 查看所有 API 资源类型及其缩写
kubectl api-resources
# 查看某个资源的详细字段说明
kubectl explain pod
kubectl explain pod.spec.containers
kubectl explain deployment.spec.strategy --recursive
# 查看集群组件健康状态(部分版本已废弃)
kubectl get componentstatuses
2.2 节点管理
# 查看所有节点
kubectl get nodes
# 查看节点详细信息(含 IP、OS、内核、容器运行时)
kubectl get nodes -o wide
# 查看单个节点详情(Conditions、Capacity、Allocatable、Events)
kubectl describe node <node-name>
# 查看节点标签
kubectl get nodes --show-labels
# 给节点添加/删除标签
kubectl label node <node-name> disk=ssd
kubectl label node <node-name> disk-
# 添加污点(阻止 Pod 调度到该节点)
kubectl taint node <node-name> key=value:NoSchedule
# 移除污点
kubectl taint node <node-name> key=value:NoSchedule-
# 标记节点为不可调度(维护前使用)
kubectl cordon <node-name>
# 驱逐节点上的 Pod(维护时使用)
kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data
# 恢复节点可调度
kubectl uncordon <node-name>
# 查看节点资源使用情况(需安装 Metrics Server)
kubectl top node
kubectl top node <node-name>
2.3 命名空间管理
# 查看所有命名空间
kubectl get namespaces
# 创建命名空间
kubectl create namespace <name>
# 删除命名空间(会删除其中所有资源,谨慎操作)
kubectl delete namespace <name>
# 查看所有命名空间的资源
kubectl get all --all-namespaces
kubectl get all -A
# 查看指定命名空间的资源
kubectl get all -n <namespace>
三、资源查询与状态查看
3.1 通用查询语法
# 基本格式
kubectl get <resource-type> [<resource-name>] [-n <namespace>] [-o <format>]
# 查看所有核心资源
kubectl get all -n <namespace>
# 按标签筛选
kubectl get pods -l app=nginx
kubectl get pods -l 'app in (nginx,redis)'
kubectl get pods -l 'env!=production'
# 按字段筛选
kubectl get pods --field-selector status.phase=Running
kubectl get pods --field-selector spec.nodeName=worker-1
# 排序
kubectl get pods --sort-by=.metadata.creationTimestamp
kubectl get pods --sort-by=.status.startTime
# 监听资源变化(实时刷新)
kubectl get pods -w
kubectl get events -w
3.2 工作负载查询
# ========== Pod ==========
kubectl get pods
kubectl get pods -o wide
kubectl get pods --all-namespaces
kubectl describe pod <pod-name>
kubectl get pod <pod-name> -o yaml
# 查看 Pod 中的容器列表
kubectl get pod <pod-name> -o jsonpath='{.spec.containers[*].name}'
# 查看 Pod 的 IP
kubectl get pod <pod-name> -o jsonpath='{.status.podIP}'
# 查看 Pod 所在节点
kubectl get pod <pod-name> -o jsonpath='{.spec.nodeName}'
# ========== Deployment ==========
kubectl get deployments
kubectl describe deployment <name>
kubectl get deployment <name> -o yaml
# 查看 Deployment 关联的 ReplicaSet
kubectl get rs -l app=<label>
# ========== StatefulSet ==========
kubectl get statefulsets
kubectl describe statefulset <name>
# ========== DaemonSet ==========
kubectl get daemonsets -A
kubectl describe daemonset <name> -n kube-system
# ========== Job / CronJob ==========
kubectl get jobs
kubectl get cronjobs
kubectl describe job <name>
3.3 网络资源查询
# ========== Service ==========
kubectl get services
kubectl get svc -o wide
kubectl describe svc <name>
# 查看 Service 的 Endpoints(后端 Pod IP 列表)
kubectl get endpoints <service-name>
kubectl get endpointslices -l kubernetes.io/service-name=<service-name>
# ========== Ingress ==========
kubectl get ingress
kubectl describe ingress <name>
# ========== NetworkPolicy ==========
kubectl get networkpolicies -A
kubectl describe networkpolicy <name>
3.4 配置与存储查询
# ========== ConfigMap ==========
kubectl get configmaps
kubectl describe configmap <name>
kubectl get configmap <name> -o yaml
# ========== Secret ==========
kubectl get secrets
kubectl describe secret <name>
# 查看 Secret 内容(Base64 解码)
kubectl get secret <name> -o jsonpath='{.data.<key>}' | base64 -d
# ========== PV / PVC ==========
kubectl get pv
kubectl get pvc -A
kubectl describe pv <name>
kubectl describe pvc <name>
# ========== StorageClass ==========
kubectl get storageclass
3.5 RBAC 资源查询
# 查看 Role / ClusterRole
kubectl get roles -A
kubectl get clusterroles
# 查看 RoleBinding / ClusterRoleBinding
kubectl get rolebindings -A
kubectl get clusterrolebindings
# 查看 ServiceAccount
kubectl get serviceaccounts -A
# 检查权限
kubectl auth can-i create pods
kubectl auth can-i create pods --as=system:serviceaccount:default:my-sa
kubectl auth can-i '*' '*' --as=admin
kubectl auth can-i list pods -n production --as=developer
四、应用部署与管理
4.1 创建与更新
# 声明式创建/更新(推荐)
kubectl apply -f <file.yaml>
kubectl apply -f <directory>/
kubectl apply -f https://raw.githubusercontent.com/...
# 命令式创建
kubectl create deployment nginx --image=nginx:1.24 --replicas=3
kubectl create service clusterip nginx --tcp=80:80
kubectl create configmap my-config --from-literal=key=value
kubectl create secret generic my-secret --from-literal=password=abc123
# 快速运行一次性 Pod
kubectl run debug --image=busybox --rm -it --restart=Never -- sh
kubectl run test --image=curlimages/curl --rm -it --restart=Never -- curl http://my-svc
# 生成 YAML 模板(不实际创建)
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > deployment.yaml
kubectl create service clusterip my-svc --tcp=80:8080 --dry-run=client -o yaml
kubectl run test --image=nginx --dry-run=client -o yaml > pod.yaml
4.2 滚动更新与回滚
# 更新镜像
kubectl set image deployment/<name> <container>=<image>:<tag>
# 查看更新状态
kubectl rollout status deployment/<name>
# 查看更新历史
kubectl rollout history deployment/<name>
kubectl rollout history deployment/<name> --revision=2
# 回滚到上一版本
kubectl rollout undo deployment/<name>
# 回滚到指定版本
kubectl rollout undo deployment/<name> --to-revision=2
# 暂停/恢复更新
kubectl rollout pause deployment/<name>
kubectl rollout resume deployment/<name>
# 重启所有 Pod(不改配置)
kubectl rollout restart deployment/<name>
4.3 扩缩容
# 手动扩缩容
kubectl scale deployment/<name> --replicas=5
# 创建 HPA
kubectl autoscale deployment/<name> --min=2 --max=10 --cpu-percent=70
# 查看 HPA
kubectl get hpa
kubectl describe hpa <name>
4.4 删除资源
# 删除单个资源
kubectl delete pod <name>
kubectl delete deployment <name>
kubectl delete -f <file.yaml>
# 强制删除卡住的 Pod
kubectl delete pod <name> --grace-period=0 --force
# 按标签批量删除
kubectl delete pods -l app=test
# 删除命名空间下所有资源
kubectl delete all --all -n <namespace>
五、日志查看与排查
5.1 Pod 日志
# 查看 Pod 日志
kubectl logs <pod-name>
# 指定容器(多容器 Pod)
kubectl logs <pod-name> -c <container-name>
# 实时跟踪日志
kubectl logs <pod-name> -f
# 查看前一个容器的日志(容器崩溃后排查)
kubectl logs <pod-name> --previous
# 显示时间戳
kubectl logs <pod-name> --timestamps
# 查看最近 1 小时的日志
kubectl logs <pod-name> --since=1h
# 查看最近 30 分钟
kubectl logs <pod-name> --since=30m
# 查看最后 100 行
kubectl logs <pod-name> --tail=100
# 按标签查看多个 Pod 的日志
kubectl logs -l app=nginx --all-containers
# 查看 Init 容器日志
kubectl logs <pod-name> -c <init-container-name>
# 查看 kube-system 组件日志
kubectl logs -n kube-system -l component=kube-apiserver
kubectl logs -n kube-system -l k8s-app=kube-dns
5.2 事件查看
# 查看当前命名空间事件(按时间排序)
kubectl get events --sort-by=.lastTimestamp
# 查看所有命名空间事件
kubectl get events -A --sort-by=.lastTimestamp
# 实时监听事件
kubectl get events -w
# 查看特定资源的事件
kubectl describe pod <pod-name> # Events 在输出末尾
kubectl describe node <node-name>
# 只看 Warning 事件
kubectl get events --field-selector type=Warning
# 查看最近 5 分钟的事件
kubectl get events --field-selector reason=FailedScheduling
六、调试与问题排查
6.1 Pod 问题排查
# 排查流程:状态 → 详情 → 日志 → 进入容器
# 1. 查看 Pod 状态
kubectl get pod <name> -o wide
# 2. 查看详细信息和 Events
kubectl describe pod <name>
# 3. 查看日志
kubectl logs <name>
kubectl logs <name> --previous # 崩溃重启时查看上次日志
# 4. 进入容器调试
kubectl exec -it <pod-name> -- /bin/sh
kubectl exec -it <pod-name> -c <container> -- /bin/bash
常见 Pod 状态及排查方向:
| 状态 | 含义 | 排查方向 |
|---|---|---|
Pending | 未被调度或正在拉取镜像 | describe pod 查看 Events:资源不足、节点污点、亲和性不满足、镜像拉取失败 |
ImagePullBackOff | 镜像拉取失败 | 检查镜像名称拼写、仓库地址、认证凭据(imagePullSecrets) |
CrashLoopBackOff | 容器反复崩溃重启 | logs --previous 查看崩溃日志:应用错误、OOMKilled、配置错误 |
OOMKilled | 内存超出 limits | 增大 resources.limits.memory 或优化应用内存使用 |
Terminating | 删除中卡住 | 检查 finalizers:kubectl get pod <name> -o jsonpath='{.metadata.finalizers}',必要时 --force 删除 |
ErrImagePull | 镜像首次拉取失败 | 同 ImagePullBackOff,但尚未进入退避重试 |
Init:Error | Init 容器失败 | logs <pod> -c <init-container> 查看 Init 容器日志 |
ContainerCreating | 容器创建中,可能卡住 | describe pod 查看是否在等待 Volume 挂载、Secret 创建等 |
6.2 网络调试
# 从临时 Pod 内测试网络连通性
kubectl run debug --image=busybox --rm -it --restart=Never -- sh
# 在容器内:
# nslookup my-svc.default.svc.cluster.local
# wget -qO- http://my-svc:80
# ping <pod-ip>
# 使用 curl 镜像
kubectl run curl --image=curlimages/curl --rm -it --restart=Never -- \
curl -s http://my-svc.default.svc.cluster.local
# 端口转发(本地访问集群内服务)
kubectl port-forward pod/<pod-name> 8080:80
kubectl port-forward svc/<svc-name> 8080:80
kubectl port-forward deployment/<deploy-name> 8080:80
# 查看 Service 是否有后端 Endpoints
kubectl get endpoints <svc-name>
# 查看 kube-proxy 模式
kubectl get configmap kube-proxy -n kube-system -o yaml | grep mode
# DNS 调试
kubectl run dns-test --image=busybox --rm -it --restart=Never -- nslookup kubernetes.default
kubectl get pods -n kube-system -l k8s-app=kube-dns
kubectl logs -n kube-system -l k8s-app=kube-dns
6.3 节点问题排查
# 查看节点状态
kubectl get nodes
# STATUS 含 NotReady 表示节点异常
# 查看节点 Conditions
kubectl describe node <node-name>
# 关注 Conditions 中的:
# Ready — 节点是否就绪
# MemoryPressure — 内存是否不足
# DiskPressure — 磁盘是否不足
# PIDPressure — PID 是否不足
# 查看节点资源分配情况
kubectl describe node <node-name> | grep -A 10 "Allocated resources"
# 查看节点上运行的 Pod
kubectl get pods --all-namespaces --field-selector spec.nodeName=<node-name>
# 查看节点事件
kubectl get events --field-selector involvedObject.kind=Node,involvedObject.name=<node-name>
6.4 控制平面组件排查
# 查看控制平面 Pod 状态
kubectl get pods -n kube-system
# API Server 日志
kubectl logs -n kube-system kube-apiserver-<master-name>
# Scheduler 日志
kubectl logs -n kube-system kube-scheduler-<master-name>
# Controller Manager 日志
kubectl logs -n kube-system kube-controller-manager-<master-name>
# etcd 日志
kubectl logs -n kube-system etcd-<master-name>
# CoreDNS 日志
kubectl logs -n kube-system -l k8s-app=kube-dns
# kube-proxy 日志
kubectl logs -n kube-system -l k8s-app=kube-proxy
七、性能分析与资源监控
# 查看节点资源使用(需 Metrics Server)
kubectl top nodes
# 查看 Pod 资源使用
kubectl top pods
kubectl top pods -n <namespace>
kubectl top pods --all-namespaces --sort-by=cpu
kubectl top pods --sort-by=memory
# 查看 Pod 内各容器资源使用
kubectl top pods --containers
# 查看资源配额使用情况
kubectl describe resourcequota -n <namespace>
# 查看 LimitRange
kubectl describe limitrange -n <namespace>
# 查看 PVC 使用情况
kubectl get pvc -A
kubectl describe pvc <name>
八、文件操作与容器交互
# 进入容器
kubectl exec -it <pod-name> -- /bin/sh
kubectl exec -it <pod-name> -c <container> -- /bin/bash
# 在容器内执行单条命令
kubectl exec <pod-name> -- ls /app
kubectl exec <pod-name> -- env
kubectl exec <pod-name> -- cat /etc/resolv.conf
# 复制文件:容器 → 本地
kubectl cp <pod-name>:/path/to/file ./local-file
kubectl cp <namespace>/<pod-name>:/var/log/app.log ./app.log
# 复制文件:本地 → 容器
kubectl cp ./local-file <pod-name>:/path/to/file
# 指定容器(多容器 Pod)
kubectl cp <pod-name>:/path/file ./file -c <container>
九、高级技巧
9.1 批量操作
# 删除所有 Evicted 状态的 Pod
kubectl get pods --all-namespaces --field-selector status.phase=Failed \
-o json | kubectl delete -f -
# 删除指定命名空间所有完成的 Job
kubectl delete jobs --field-selector status.successful=1 -n <namespace>
# 重启某个命名空间下所有 Deployment
kubectl get deployments -n <namespace> -o name | \
xargs -I {} kubectl rollout restart {} -n <namespace>
# 查看所有未就绪的 Pod
kubectl get pods -A | grep -v Running | grep -v Completed
9.2 标签与注解操作
# 添加标签
kubectl label pod <name> env=production
kubectl label node <name> zone=east
# 修改标签(覆盖已有值)
kubectl label pod <name> env=staging --overwrite
# 删除标签
kubectl label pod <name> env-
# 添加注解
kubectl annotate pod <name> description="my app"
kubectl annotate deployment <name> kubernetes.io/change-cause="update to v2"
# 删除注解
kubectl annotate pod <name> description-
9.3 资源 Patch
# JSON Patch(精确修改某个字段)
kubectl patch deployment <name> -p '{"spec":{"replicas":5}}'
# Strategic Merge Patch(合并修改)
kubectl patch deployment <name> -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","image":"nginx:1.25"}]}}}}'
# JSON Patch 类型
kubectl patch deployment <name> --type=json \
-p='[{"op":"replace","path":"/spec/replicas","value":5}]'
9.4 等待条件
# 等待 Pod 就绪
kubectl wait --for=condition=Ready pod/<name> --timeout=120s
# 等待 Deployment 完成
kubectl wait --for=condition=Available deployment/<name> --timeout=300s
# 等待 Pod 删除完成
kubectl wait --for=delete pod/<name> --timeout=60s
# 等待 Job 完成
kubectl wait --for=condition=Complete job/<name> --timeout=600s
9.5 diff 与 dry-run
# 对比本地 YAML 与集群实际状态的差异
kubectl diff -f deployment.yaml
# 模拟执行(不实际创建/修改)
kubectl apply -f deployment.yaml --dry-run=client
kubectl apply -f deployment.yaml --dry-run=server # 服务端校验,更精确
十、常用排查 SOP
10.1 Pod 无法启动排查流程
上图展示了 Pod 无法启动时的排查决策树,根据 Pod 状态选择不同的排查路径。
10.2 Service 无法访问排查流程
上图展示了 Service 无法访问时的排查流程,从 Endpoints 是否存在开始逐步定位。
10.3 节点 NotReady 排查流程
上图展示了节点 NotReady 的排查路径,从节点 Conditions 出发定位具体原因。
十一、kubectl 插件推荐
| 插件 | 用途 | 安装 |
|---|---|---|
| kubectl-neat | 清理 kubectl get -o yaml 输出中的冗余字段 | kubectl krew install neat |
| kubectl-tree | 以树形展示资源的 ownerReferences 关系 | kubectl krew install tree |
| kubectl-images | 查看集群中使用的所有容器镜像 | kubectl krew install images |
| kubectl-who-can | 查看谁有权限执行某操作 | kubectl krew install who-can |
| kubectx / kubens | 快速切换 context 和 namespace | brew install kubectx |
| stern | 多 Pod 日志聚合查看 | brew install stern |
| k9s | 终端 UI 管理工具 | brew install k9s |
# 安装 krew(kubectl 插件管理器)
# https://krew.sigs.k8s.io/docs/user-guide/setup/install/
# 使用示例
kubectl neat get pod <name> -o yaml # 输出清洁的 YAML
kubectl tree deployment <name> # 树形展示资源关系
kubectl who-can create pods # 查看谁能创建 Pod
stern <pod-prefix> -n <namespace> # 聚合多 Pod 日志
十二、总结速查表
| 场景 | 命令 |
|---|---|
| 查看集群信息 | kubectl cluster-info |
| 查看所有节点 | kubectl get nodes -o wide |
| 查看所有 Pod | kubectl get pods -A |
| 查看 Pod 日志 | kubectl logs <pod> [-c container] [-f] [--previous] |
| 查看资源详情 | kubectl describe <type> <name> |
| 进入容器 | kubectl exec -it <pod> -- /bin/sh |
| 端口转发 | kubectl port-forward svc/<name> 8080:80 |
| 更新镜像 | kubectl set image deployment/<name> <container>=<image> |
| 回滚 | kubectl rollout undo deployment/<name> |
| 扩缩容 | kubectl scale deployment/<name> --replicas=N |
| 查看事件 | kubectl get events --sort-by=.lastTimestamp |
| 查看资源使用 | kubectl top pods / kubectl top nodes |
| 生成 YAML 模板 | kubectl create <type> --dry-run=client -o yaml |
| 对比差异 | kubectl diff -f <file.yaml> |
| 权限检查 | kubectl auth can-i <verb> <resource> [--as=<user>] |
| 等待就绪 | kubectl wait --for=condition=Ready pod/<name> |
| 强制删除 | kubectl delete pod <name> --grace-period=0 --force |
| 重启 Pod | kubectl rollout restart deployment/<name> |
1万+

被折叠的 条评论
为什么被折叠?



