本页目录

Kubernetes 操作手册

Kubernetes 是容器编排平台。核心概念: pod (最小调度单元), deployment (声明式 pod 管理), service (稳定网络入口), ingress (L7 路由), configmap/secret (配置注入), namespace (资源隔离)。

查看

# 节点
kubectl get nodes -o wide                               # 含 IP, OS, kubelet 版本
kubectl describe node <node>                            # 容量, 条件, 事件

# Pod
kubectl get pods -A                                     # 所有 namespace
kubectl get pods -n <ns> -o wide                        # 含 IP, node, status
kubectl get pods -n <ns> --sort-by=.status.startTime    # 按创建时间排
kubectl get pods -n <ns> --field-selector status.phase=Running

# 描述 (最常用调试命令: 看 Events 知道哪里卡了)
kubectl describe pod <pod> -n <ns>
# Events 解读:
#   FailedScheduling → 资源不够或 node affinity 不匹配
#   Failed to pull image → 镜像名/版本错了或 registry 不可达
#   CrashLoopBackOff → 容器启动后立即退出 (看 logs)

# 日志
kubectl logs <pod> -n <ns> --tail=100 -f
kubectl logs <pod> -n <ns> --previous                    # 上次崩溃的日志
kubectl logs -l app=myapp -n <ns> --tail=50              # 标签选择器

# 其他资源
kubectl get deploy,svc,ingress,cm,secret,pvc -n <ns>
kubectl get events -n <ns> --sort-by='.lastTimestamp'    # namespace 内所有事件
kubectl top pods -A                                      # 资源使用 (需 metrics-server)
kubectl config get-contexts                              # 当前 kubeconfig 上下文

操作

kubectl apply -f manifest.yaml                           # 创建/更新
kubectl delete -f manifest.yaml
kubectl delete pod <pod> -n <ns>                        # 删 pod (deployment 会重建)
kubectl rollout restart deployment/<name> -n <ns>        # 滚动重启
kubectl scale deployment/<name> --replicas=3 -n <ns>

kubectl exec -it <pod> -n <ns> -- sh
kubectl exec <pod> -n <ns> -- cat /etc/config
kubectl cp <pod>:/path/file ./file -n <ns>
kubectl port-forward <pod> 8080:80 -n <ns>               # 本地调试
kubectl config use-context <context>

调试

# pod 起不来: 看 Events
kubectl describe pod <pod> -n <ns> | tail -20

# 看完整 yaml (含默认值 + 运行时状态)
kubectl get pod <pod> -n <ns> -o yaml

# 临时调试容器
kubectl run debug --rm -it --image=alpine -- sh

# RBAC 权限检查
kubectl auth can-i create pods --as=system:serviceaccount:<ns>:<sa>