掌握 Kubernetes 命令行工具 kubectl 是管理容器化集群的核心。本文将系统解析从集群状态查看、应用部署管理到故障排查与性能优化的必备命令,帮助你高效运维生产环境。
🚀 快速导航
- • 基础集群信息查看
- • Pod 生命周期管理
- • 服务与网络管理
- • 存储与配置管理
- • 故障排查神技
- • 性能监控与优化
- • 高级运维技巧
基础集群信息查看
集群状态总览
# 查看集群信息
kubectl cluster-info
# 查看节点状态
kubectl get nodes -o wide
# 查看节点详细信息
kubectl describe node <node-name>
# 查看集群资源使用情况
kubectl top nodes
kubectl top pods --all-namespaces
命名空间管理
# 查看所有命名空间
kubectl get namespaces
# 创建命名空间
kubectl create namespace <namespace-name>
# 删除命名空间(谨慎操作)
kubectl delete namespace <namespace-name>
# 设置默认命名空间
kubectl config set-context --current --namespace=<namespace-name>
技巧提示: 使用 kubectl config view --minify | grep namespace 可快速查看当前命名空间。
Pod 生命周期管理
Pod 基础操作
# 查看所有 Pod
kubectl get pods --all-namespaces
# 查看指定命名空间的 Pod
kubectl get pods -n <namespace>
# 实时监控 Pod 状态变化
kubectl get pods -w
# 查看 Pod 详细信息
kubectl describe pod <pod-name> -n <namespace>
# 删除 Pod
kubectl delete pod <pod-name> -n <namespace>
# 强制删除卡住的 Pod
kubectl delete pod <pod-name> --grace-period=0 --force
Pod 高级查询
# 按标签选择器查询
kubectl get pods -l app=nginx
# 按字段选择器查询
kubectl get pods --field-selector status.phase=Running
# 查看 Pod 的 YAML 配置
kubectl get pod <pod-name> -o yaml
# 查看 Pod 资源使用情况
kubectl top pod <pod-name>
# 查看所有容器状态
kubectl get pods -o jsonpath='{range .items}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
运维提示: 使用 kubectl get pods --sort-by=.metadata.creationTimestamp 按创建时间排序,便于快速定位新部署的应用。
服务与网络管理
Service 服务管理
# 查看所有服务
kubectl get services --all-namespaces
# 查看服务详细信息
kubectl describe service <service-name>
# 查看服务端点
kubectl get endpoints <service-name>
# 临时端口转发(调试神器)
kubectl port-forward pod/<pod-name> 8080:80
kubectl port-forward service/<service-name> 8080:80
# 查看服务的选择器匹配的 Pod
kubectl get pods -l <service-selector>
Ingress 管理
# 查看 Ingress 规则
kubectl get ingress --all-namespaces
# 查看 Ingress 详细配置
kubectl describe ingress <ingress-name>
# 查看 Ingress 控制器日志
kubectl logs -n ingress-nginx deployment/nginx-ingress-controller
网络策略与排查
# 查看网络策略
kubectl get networkpolicies --all-namespaces
# 测试 Pod 间网络连通性
kubectl exec -it <pod-name> -- ping <target-ip>
kubectl exec -it <pod-name> -- nslookup <service-name>
# 查看 DNS 配置
kubectl exec -it <pod-name> -- cat /etc/resolv.conf
存储与配置管理
ConfigMap 和 Secret
# 查看配置映射
kubectl get configmaps --all-namespaces
# 查看 ConfigMap 内容
kubectl describe configmap <configmap-name>
kubectl get configmap <configmap-name> -o yaml
# 创建 ConfigMap
kubectl create configmap <name> --from-file=<file-path>
kubectl create configmap <name> --from-literal=key=value
# 查看密钥
kubectl get secrets --all-namespaces
# 查看 Secret 内容(Base64 解码)
kubectl get secret <secret-name> -o jsonpath='{.data.password}' | base64 -d
持久化存储
# 查看持久卷
kubectl get pv
# 查看持久卷声明
kubectl get pvc --all-namespaces
# 查看存储类
kubectl get storageclass
# 查看卷详细信息
kubectl describe pv <pv-name>
kubectl describe pvc <pvc-name>
性能提示: 使用自定义列输出命令可快速查看存储概况,这是运维/DevOps工作中提升效率的实用技巧。
故障排查神技
日志查看与分析
# 查看 Pod 日志
kubectl logs <pod-name> -n <namespace>
# 查看多容器 Pod 的特定容器日志
kubectl logs <pod-name> -c <container-name>
# 实时跟踪日志
kubectl logs -f <pod-name>
# 查看之前崩溃容器的日志
kubectl logs <pod-name> --previous
# 查看最近指定时间的日志
kubectl logs <pod-name> --since=1h
kubectl logs <pod-name> --since-time=2024-01-01T00:00:00Z
# 导出所有 Pod 日志
for pod in $(kubectl get pods -o name); do
kubectl logs $pod > ${pod##*/}.log 2>&1
done
容器调试
# 进入容器 Shell
kubectl exec -it <pod-name> -- /bin/bash
kubectl exec -it <pod-name> -- /bin/sh
# 在多容器 Pod 中指定容器
kubectl exec -it <pod-name> -c <container-name> -- /bin/bash
# 复制文件到/从容器
kubectl cp <local-file> <pod-name>:<container-path>
kubectl cp <pod-name>:<container-path> <local-file>
# 临时运行调试容器
kubectl run debug-pod --rm -it --image=busybox -- /bin/sh
# 在现有网络命名空间中运行调试容器
kubectl debug <pod-name> -it --image=nicolaka/netshoot
事件与状态分析
# 查看集群事件
kubectl get events --sort-by='.lastTimestamp'
# 查看特定资源的事件
kubectl describe <resource-type> <resource-name>
# 监控资源变化
kubectl get pods -w
kubectl get events -w
# 查看资源使用情况
kubectl describe node <node-name> | grep -A 5 "Allocated resources"
故障定位标准流程:
- 查看 Pod 状态:
kubectl get pods
- 查看事件详情:
kubectl describe pod <pod-name>
- 查看应用日志:
kubectl logs <pod-name>
- 进入容器调试:
kubectl exec -it <pod-name> -- /bin/bash
性能监控与优化
资源监控
# 查看节点资源使用
kubectl top nodes
# 查看 Pod 资源使用
kubectl top pods --all-namespaces
# 查看特定命名空间资源使用
kubectl top pods -n <namespace>
# 按 CPU 使用率排序
kubectl top pods --sort-by=cpu
# 按内存使用率排序
kubectl top pods --sort-by=memory
扩缩容管理
# 手动扩缩容 Deployment
kubectl scale deployment <deployment-name> --replicas=5
# 查看 HPA(水平自动扩缩容)
kubectl get hpa
# 查看 VPA(垂直自动扩缩容)
kubectl get vpa
# 查看 Deployment 滚动更新状态
kubectl rollout status deployment/<deployment-name>
# 查看滚动更新历史
kubectl rollout history deployment/<deployment-name>
# 回滚到上一个版本
kubectl rollout undo deployment/<deployment-name>
资源配额管理
# 查看资源配额
kubectl get resourcequota --all-namespaces
# 查看 LimitRange
kubectl get limitrange --all-namespaces
# 查看资源配额详情
kubectl describe resourcequota <quota-name>
高级运维技巧
批量操作与自动化
# 批量删除状态为 Evicted 的 Pod
kubectl get pods --all-namespaces | grep Evicted | awk '{print $1, $2}' | xargs -n2 kubectl delete pod -n
# 批量重启所有 Deployment
kubectl get deployments -o name | xargs -I {} kubectl rollout restart {}
# 批量获取所有 Pod 的镜像信息
kubectl get pods --all-namespaces -o jsonpath='{range .items}{.metadata.name}{"\t"}{.spec.containers.image}{"\n"}{end}'
# 查找没有设置资源限制的 Pod
kubectl get pods --all-namespaces -o json | jq '.items[] | select(.spec.containers[].resources.limits == null) | .metadata.name'
安全与权限管理
# 查看当前用户权限
kubectl auth can-i --list
# 检查特定用户权限
kubectl auth can-i create pods --as=<username>
# 查看 RBAC 角色
kubectl get roles,rolebindings --all-namespaces
kubectl get clusterroles,clusterrolebindings
# 查看服务账户
kubectl get serviceaccounts --all-namespaces
# 查看安全策略
kubectl get podsecuritypolicies
集群维护与备份
# 驱逐节点(维护前)
kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data
# 标记节点不可调度
kubectl cordon <node-name>
# 恢复节点调度
kubectl uncordon <node-name>
# 导出资源配置(备份)
kubectl get all --all-namespaces -o yaml > cluster-backup.yaml
# 导出特定资源类型
kubectl get configmaps --all-namespaces -o yaml > configmaps-backup.yaml
kubectl get secrets --all-namespaces -o yaml > secrets-backup.yaml
性能调优命令
# 查看集群组件状态
kubectl get componentstatuses
# 查看 API Server 指标
kubectl get --raw /metrics
# 查看调度器队列
kubectl get events --field-selector reason=FailedScheduling
# 分析 Pod 启动时间
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,START_TIME:.status.startTime,NODE:.spec.nodeName
🛠️ 实用技巧锦囊
命令行优化
# 设置别名提高效率
alias k='kubectl'
alias kgp='kubectl get pods'
alias kgs='kubectl get services'
alias kgn='kubectl get nodes'
alias kdp='kubectl describe pod'
alias kl='kubectl logs'
# 使用 kubectx 快速切换集群
kubectx <cluster-name>
# 使用 kubens 快速切换命名空间
kubens <namespace-name>
合理使用别名是提升云原生/IaaS平台运维效率的有效手段。
输出格式化
# JSON 输出
kubectl get pods -o json
# YAML 输出
kubectl get pods -o yaml
# 自定义列输出
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName
# 使用 JSONPath 提取特定字段
kubectl get pods -o jsonpath='{.items.metadata.name}'
# 格式化输出(需要 jq)
kubectl get pods -o json | jq '.items[] | {name: .metadata.name, status: .status.phase}'
📚 总结与最佳实践
日常运维检查清单
- 集群健康检查
- 节点状态:
kubectl get nodes
- 系统 Pod:
kubectl get pods -n kube-system
- 资源使用:
kubectl top nodes
- 应用状态监控
- Pod 状态:
kubectl get pods --all-namespaces
- 服务状态:
kubectl get services --all-namespaces
- 事件监控:
kubectl get events --sort-by='.lastTimestamp'
- 性能优化检查
- 资源配额:
kubectl describe node <node-name>
- HPA 状态:
kubectl get hpa
- 存储使用:
kubectl get pvc --all-namespaces
安全运维准则
- 定期备份关键配置:ConfigMap、Secret、PV
- 设置合理的资源限制和配额
- 监控异常事件和失败的调度
- 及时清理不需要的资源和镜像
- 保持集群组件版本更新
熟练掌握这些 kubectl 命令,是保障 Kubernetes 集群稳定、高效运行的基础。它们不仅能提升日常工作效率,更是快速定位与解决线上问题的关键工具。作为强大的云原生编排平台,Kubernetes 的深度使用离不开对其命令行工具的透彻理解。