Kubernetes 使用指南 — 各类场景命令全解 Kubernetes(简称 K8s)是当前业界标准的容器编排平台。无论你是刚入门的学习者,还是日常运维的一线工程师,掌握 kubectl 的核心命令都至关重要。
本文将按照 实际场景 组织命令,告别枯燥的 API 罗列,让你遇到问题时能快速找到对应「武器」。
K8s 架构简览 flowchart LR subgraph Control Plane API[API Server] S[Scheduler] CM[Controller Manager] ETCD[(etcd)] end subgraph Worker Nodes K[Kubelet] P1[Pod A] P2[Pod B] end subgraph Network SVC[Service] ING[Ingress] end API --> S API --> CM API --> K CM --> P1 CM --> P2 S --> K K --> P1 K --> P2 P1 -.-> SVC P2 -.-> SVC SVC -.-> ING
控制平面 (Control Plane)负责决策与调度,工作节点 (Worker Node)负责运行容器。本文的命令覆盖两端的常用操作。
一、集群信息与节点管理 kubectl cluster-info kubectl get nodes kubectl get nodes -o wide kubectl get node <node-name> -o yaml kubectl describe node <node-name> kubectl cordon <node-name> kubectl uncordon <node-name> kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data kubectl top node
场景:节点维护 当需要重启或升级某台服务器时:
kubectl cordon node-01 kubectl drain node-01 --ignore-daemonsets --delete-emptydir-data kubectl uncordon node-01
二、Pod 管理 Pod 是 K8s 最小的部署单元。
kubectl apply -f pod.yaml kubectl get pods --all-namespaces kubectl get pods kubectl get pods -o wide kubectl get pods -o yaml kubectl get pods --watch kubectl describe pod <pod-name> kubectl delete pod <pod-name> kubectl delete pod <pod-name> --force --grace-period=0 kubectl logs <pod-name> kubectl logs -f <pod-name> kubectl logs <pod-name> --previous kubectl logs <pod-name> -c <container-name> kubectl exec -it <pod-name> -- /bin/sh kubectl exec -it <pod-name> -- /bin/bash kubectl exec <pod-name> -- cat /etc/config kubectl cp /local/path/file.txt <pod-name>:/remote/path/ kubectl cp <pod-name>:/remote/path/file.txt /local/path/ kubectl top pod kubectl top pod --containers
场景:Pod 一直 Pending kubectl describe pod <pod-name> kubectl top node kubectl get pvc kubectl describe node <node-name> | findstr Taints
场景:Pod 反复 CrashLoopBackOff kubectl logs <pod-name> --previous kubectl describe pod <pod-name> kubectl exec -it <pod-name> -- /bin/sh
三、Deployment 管理 kubectl create deployment nginx --image=nginx:1.25 kubectl apply -f deployment.yaml kubectl get deployments kubectl get deployment <name> -o wide kubectl describe deployment <name> kubectl get rs kubectl scale deployment <name> --replicas=5 kubectl autoscale deployment <name> --min=2 --max=10 --cpu-percent=80 kubectl set image deployment/<name> nginx=nginx:1.26 kubectl rollout status deployment/<name> kubectl rollout history deployment/<name> kubectl rollout undo deployment/<name> kubectl rollout undo deployment/<name> --to-revision=2 kubectl rollout pause deployment/<name> kubectl rollout resume deployment/<name> kubectl delete deployment <name>
场景:滚动更新策略 spec: replicas: 5 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0
kubectl set image deployment/myapp myapp=myapp:v2 kubectl rollout status deployment/myapp --watch
场景:金丝雀发布 kubectl scale deployment myapp-stable --replicas=9 kubectl scale deployment myapp-canary --replicas=1 kubectl set image deployment/myapp-stable myapp=myapp:v2 kubectl scale deployment/myapp-canary --replicas=0
四、Service 网络管理 kubectl expose deployment nginx --port=80 --target-port=80 kubectl expose deployment nginx --port=80 --target-port=80 --type =NodePort kubectl expose deployment nginx --port=80 --target-port=80 --type =LoadBalancer kubectl get services kubectl get svc -o wide kubectl get endpoints kubectl describe svc <service-name> kubectl delete svc <service-name>
场景:Service 类型选择
类型
访问方式
适用场景
ClusterIP
service-ip:port(仅集群内)
内部服务通信
NodePort
节点IP:NodePort
外部调试 / 本地开发
LoadBalancer
云厂商 LB 提供外网 IP
生产对外服务
ExternalName
CNAME 到外部域名
引入外部服务
Headless Service(有状态应用) apiVersion: v1 kind: Service metadata: name: myapp-headless spec: clusterIP: None selector: app: myapp ports: - port: 80
可通过 DNS 直接拿到 Pod IP 列表:
kubectl exec -it pod-shell -- nslookup myapp-headless
五、Ingress 流量接入 kubectl get ingress kubectl describe ingress <name> kubectl get ingressclass
常见 Ingress 配置示例 apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: myapp-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: ingressClassName: nginx rules: - host: myapp.example.com http: paths: - path: /api pathType: Prefix backend: service: name: api-service port: number: 80 - path: / pathType: Prefix backend: service: name: web-service port: number: 8080
kubectl apply -f ingress.yaml
六、ConfigMap 与 Secret kubectl create configmap app-config --from-file=config.properties kubectl create configmap app-config --from-literal=APP_ENV=production --from-literal=LOG_LEVEL=info kubectl create secret generic db-secret --from-literal=username=admin --from-literal=password=s3cret kubectl create secret generic tls-secret --from-file=tls.crt --from-file=tls.key kubectl get configmaps kubectl describe configmap <name> kubectl get configmap <name> -o yaml kubectl get secrets kubectl describe secret <name> kubectl get secret <name> -o yaml
Pod 中挂载 ConfigMap spec: containers: - name: myapp image: myapp:1.0 env: - name: APP_ENV valueFrom: configMapKeyRef: name: app-config key: APP_ENV envFrom: - configMapRef: name: app-config volumeMounts: - name: config-volume mountPath: /etc/config volumes: - name: config-volume configMap: name: app-config
七、存储(PV / PVC) kubectl get pv kubectl get pvc kubectl get storageclass kubectl delete pvc <name> kubectl patch pvc <name> -p '{"metadata":{"finalizers":[]}}'
动态供应示例 apiVersion: v1 kind: PersistentVolumeClaim metadata: name: data-pvc spec: storageClassName: standard accessModes: - ReadWriteOnce resources: requests: storage: 10Gi
spec: containers: - name: myapp volumeMounts: - mountPath: /data name: data-volume volumes: - name: data-volume persistentVolumeClaim: claimName: data-pvc
八、命名空间与资源隔离 kubectl get namespaces kubectl create namespace staging kubectl config set-context --current --namespace=staging kubectl get pods -n staging ping web-service.production.svc.cluster.local kubectl api-resources --verbs=list --namespaced -o name | ForEach-Object { kubectl get $_ -n staging } kubectl delete namespace staging
九、标签与选择器 kubectl label pod my-pod version=v2 env =prod kubectl label pod my-pod version=v3 --overwrite kubectl get pods -l env =prod kubectl get pods -l 'env=prod,version=v2' kubectl get pods -l 'env in (prod,staging)' kubectl get pods --show-labels kubectl label pod my-pod version- kubectl label node node-01 disktype=ssd
节点选择器(Pod 调度到特定节点) spec: nodeSelector: disktype: ssd
十、排错与调试 kubectl get events --sort-by='.lastTimestamp' kubectl get events --watch kubectl describe pod <name> kubectl get pods -v=6 kubectl get pods -v=8 kubectl get pods -v=9 kubectl run -it dns-test --image=busybox --rm -- sh kubectl run debug-pod --image=nicolaka/netshoot --rm -it -- /bin/bash
捕获网络流量 kubectl exec <pod-name> -- tcpdump -i eth0 -w /tmp/capture.pcap kubectl cp <pod-name>:/tmp/capture.pcap ./capture.pcap
端口转发(本地调试) kubectl port-forward pod/<pod-name> 8080:80 kubectl port-forward svc/<service-name> 8080:80 kubectl port-forward deployment/<deployment-name> 8080:80
十一、污点与容忍度 kubectl taint nodes node-01 key=value:NoSchedule kubectl describe node node-01 | findstr Taints kubectl taint nodes node-01 key:NoSchedule- kubectl taint nodes node-01 key=value:NoSchedule-
Pod 通过 tolerations 容忍污点:
spec: tolerations: - key: "key" operator: "Equal" value: "value" effect: "NoSchedule"
十二、RBAC 权限控制 kubectl get roles --all-namespaces kubectl get clusterroles kubectl get rolebindings --all-namespaces kubectl get clusterrolebindings kubectl auth can-i create pods kubectl auth can-i delete deployments --as system:serviceaccount:default:my-sa kubectl create serviceaccount deployer kubectl describe serviceaccount deployer
常见 RBAC 配置 apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: default name: pod-reader rules: - apiGroups: ["" ] resources: ["pods" , "pods/log" ] verbs: ["get" , "list" , "watch" ] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: namespace: default name: pod-reader-binding subjects: - kind: ServiceAccount name: deployer namespace: default roleRef: kind: Role name: pod-reader apiGroup: rbac.authorization.k8s.io
十三、常用 YAML 速查 最小 Pod apiVersion: v1 kind: Pod metadata: name: nginx spec: containers: - name: nginx image: nginx:1.25 ports: - containerPort: 80
完整 Deployment apiVersion: apps/v1 kind: Deployment metadata: name: myapp labels: app: myapp spec: replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp image: myapp:latest ports: - containerPort: 8080 env: - name: DB_HOST value: "mysql-service" resources: requests: cpu: 100m memory: 128Mi limits: cpu: 500m memory: 512Mi livenessProbe: httpGet: path: /health port: 8080 initialDelaySeconds: 10 periodSeconds: 5 readinessProbe: httpGet: path: /ready port: 8080 initialDelaySeconds: 5 periodSeconds: 5
Service + Deployment 完整示例 apiVersion: apps/v1 kind: Deployment metadata: name: web spec: replicas: 3 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: web image: nginx:1.25 ports: - containerPort: 80 --- apiVersion: v1 kind: Service metadata: name: web-service spec: selector: app: web ports: - port: 80 targetPort: 80 type: ClusterIP
十四、Job 与 CronJob kubectl create job my-job --image=busybox -- echo "hello" kubectl get jobs kubectl create cronjob backup --image=busybox --schedule="0 2 * * *" -- dump kubectl get cronjobs kubectl create job --from=cronjob/backup manual-backup-001
十五、K8s 常用别名与快捷键 在 shell 中配置别名能极大提升效率:
alias k='kubectl' alias kg='kubectl get' alias kgp='kubectl get pods' alias kgs='kubectl get svc' alias kd='kubectl describe' alias kdp='kubectl describe pod' alias kaf='kubectl apply -f' alias kdf='kubectl delete -f' alias kl='kubectl logs' alias klf='kubectl logs -f' alias kex='kubectl exec -it' alias kpf='kubectl port-forward' alias kgn='kubectl get nodes' alias ke='kubectl get events --sort-by=.lastTimestamp' source <(kubectl completion bash)kubectl completion powershell | Out-String | Invoke-Expression alias kns='kubectl config set-context --current --namespace'
十六、集群外 kubectl 配置 kubectl config view kubectl config current-context kubectl config use-context <context-name> kubectl config set-cluster my-cluster --server=https://1.2.3.4:6443 --certificate-authority=ca.crt kubectl config set-credentials my-user --client-certificate=client.crt --client-key=client.key kubectl config set-context my-context --cluster=my-cluster --user=my-user export KUBECONFIG=~/.kube/config:~/.kube/config-prodkubectl config view --flatten > ~/.kube/config-merged
总结
场景
关键命令
查看集群
kubectl cluster-info / kubectl get nodes
部署应用
kubectl apply -f deployment.yaml
查看 Pod
kubectl get pods -o wide
排查问题
kubectl describe pod / kubectl logs -f
扩缩容
kubectl scale deployment --replicas=N
滚动更新
kubectl set image deployment
暴露服务
kubectl expose deployment --type=NodePort
本地调试
kubectl port-forward pod/xxx 8080:80
进入容器
kubectl exec -it pod -- /bin/sh
配置管理
kubectl create configmap/secret
权限控制
kubectl auth can-i / kubectl create serviceaccount
小提示 :加 --help 是学习 kubectl 最好的方式。例如 kubectl run --help 会列出所有参数与示例,比任何文档都更快。
掌握以上命令,你就能应对日常 90% 以上的 K8s 运维场景。建议收藏本文,需要时快速查阅 🐦