跳到主要内容

Kubernetes 运维常用命令速查

在日常 Kubernetes (K8s) 集群运维中,熟练掌握 kubectl 命令行工具是保障工作效率的关键。本文整理了最常用的诊断与运维命令。


0. 资源缩写表​

大部分 kubectl 命令支持资源缩写,输入更快:

缩写完整资源缩写完整资源
popodssvcservices
deploydeploymentsependpoints
stsstatefulsetsepsendpointslices
dsdaemonsetsingingresses
rsreplicasetsnetpolnetworkpolicies
cmconfigmapspvpersistentvolumes
nsnamespacespvcpersistentvolumeclaims
saserviceaccountsscstorageclasses
nonodescjcronjobs
kubectl get po,svc,deploy -n learning # 多资源一次查询
kubectl api-resources # 查看所有可用资源和缩写

1. 资源状态查看​

节点状态​

kubectl get nodes -o wide
kubectl top nodes
kubectl describe node <node-name> # 关注 Conditions 中的压力信号

Pod 状态​

kubectl get pods -n kube-system
kubectl get pods -A -o wide
kubectl get pods -n learning -w # 实时 watch

# 自定义列:只显示关心的字段
kubectl get pods -A -o custom-columns=\
NAME:.metadata.name,\
NODE:.spec.nodeName,\
RESTARTS:.status.containerStatuses[0].restartCount,\
QOS:.status.qosClass

工作负载​

kubectl get deploy,sts,ds,job,cronjob -n learning
kubectl get replicaset -n learning # 查看版本历史对应的 RS

2. 故障诊断与日志分析​

查看资源详情​

当 Pod 状态为 Pending、ImagePullBackOff 或 CrashLoopBackOff 时,首先使用 describe 命令查看事件:

kubectl describe pod <pod-name> -n <namespace>
kubectl get events -n <namespace> --sort-by=.lastTimestamp
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp

容器日志​

kubectl logs <pod-name> -n <namespace>
kubectl logs -f --tail=100 <pod-name> -n <namespace>
kubectl logs <pod-name> -c <container-name> -n <namespace> # 多容器必须 -c
kubectl logs <pod-name> --previous -n <namespace> # 崩溃容器的日志
kubectl logs deployment/<deploy-name> -n <namespace> # 聚合日志
kubectl logs job/<job-name> -n <namespace>

退出码与状态​

# 看退出码(137=OOMKilled, 143=SIGTERM, 1=应用错误)
kubectl get pod <pod-name> -n <namespace> \
-o jsonpath='{.status.containerStatuses[*].lastState.terminated.exitCode}'

# 看 QoS 等级
kubectl get pod <pod-name> -n <namespace> \
-o jsonpath='{.status.qosClass}'

3. 运维排查与调试​

进入容器​

kubectl exec -it <pod-name> -n <namespace> -- /bin/bash
kubectl exec <pod-name> -n <namespace> -c <container> -- <command>

# 精简镜像无 shell?注入临时调试容器
kubectl debug <pod-name> -n <namespace> \
--image=busybox:1.36 --target=<container-name> -it -- sh

临时转发和测试​

# 端口转发
kubectl port-forward svc/my-service 8080:80 -n learning

# 临时 Pod 做网络测试
kubectl run tmp --image=busybox:1.36 --rm -it --restart=Never -- sh
# 进入后:nslookup svc.namespace / wget -O- http://svc:port / nc -zv svc port

# 临时 Pod 带调试工具(推荐 netshoot 替代 busybox)
kubectl run tmp --image=nicolaka/netshoot --rm -it --restart=Never -- bash

权限检查​

kubectl auth can-i create deployments -n learning
kubectl auth can-i delete namespaces
kubectl auth can-i get secrets -n learning \
--as=system:serviceaccount:learning:api # 测试 ServiceAccount 权限

节点维护​

kubectl cordon <node-name> # 标记不可调度
kubectl drain <node-name> \
--ignore-daemonsets --delete-emptydir-data # 驱逐工作负载
kubectl drain <node-name> --dry-run=client # 预览会驱逐哪些 Pod
kubectl uncordon <node-name> # 恢复调度

4. 发布与配置操作​

发布管理​

kubectl apply -f manifest.yaml
kubectl rollout status deployment/api -n learning --timeout=5m
kubectl rollout history deployment/api -n learning
kubectl rollout undo deployment/api -n learning
kubectl rollout undo deployment/api -n learning --to-revision=3 # 指定版本
kubectl rollout pause deployment/api -n learning # 金丝雀暂停
kubectl rollout resume deployment/api -n learning # 金丝雀继续
kubectl rollout restart deployment/api -n learning # 触发滚动重启

在线编辑​

kubectl edit deployment/<deployment-name> -n <namespace>
kubectl set image deployment/api api=registry.example.com/api:1.4.3 -n learning
kubectl scale deployment/api --replicas=5 -n learning

配置与密钥​

kubectl create configmap my-config --from-file=app.yaml -n learning
kubectl create secret generic my-secret \
--from-literal=API_KEY=xxx -n learning
kubectl create secret tls my-tls \
--cert=cert.pem --key=key.pem -n learning

5. 实用技巧​

kubectl 插件(通过 krew 安装)​

# krew 是 kubectl 的包管理器:https://krew.sigs.k8s.io/
kubectl krew install neat # 去除运行时字段,输出干净的 YAML
kubectl krew install tree # 按层级展示资源关系
kubectl krew install sniff # 在 Pod 上抓包
kubectl krew install view-secret # 解码 Secret 值

kubectl neat get pod <pod> -o yaml
kubectl tree deployment api -n learning

常用别名​

alias k=kubectl
alias kn='kubectl config set-context --current --namespace'
alias kx='kubectl config use-context'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kl='kubectl logs'
alias ke='kubectl exec -it'

# 加进 ~/.bashrc 或 ~/.zshrc

一行诊断脚本​

# 检查所有 Namespace 的异常 Pod
kubectl get pods -A --field-selector=status.phase!=Running \
| grep -v -E 'Completed|Succeeded|Evicted'

# 查看最近 20 条 Warning 事件
kubectl get events -A --field-selector type=Warning \
--sort-by=.lastTimestamp | tail -20

# 查看节点资源使用排行
kubectl top pods -A --sort-by=cpu | tail -20
kubectl top pods -A --sort-by=memory | tail -20

6. 补充命令​

# 了解资源定义
kubectl explain deployment.spec.strategy.rollingUpdate

# 预览 apply 的变更(类似 terraform plan)
kubectl diff -f manifest.yaml

# 跨 Namespace 查看所有资源
kubectl get all -n learning # "all" 不包括 ConfigMap、Secret、PVC 等

# 用标签过滤
kubectl get pods -A -l app.kubernetes.io/name=api

# 输出为 YAML/JSON
kubectl get deployment api -n learning -o yaml > backup.yaml

# 查看 API 资源版本(升级前检查)
kubectl api-resources --sort-by=group
kubectl api-versions