kubectl 的命令按「管上下文 / 看资源 / 查日志 / 改资源」四类记最省事。下面按用途分组,版本基准 kubectl 1.28+。
上下文与集群
config 子命令只读写 kubeconfig 文件,不访问集群。
1 2 3 4 5 6
| kubectl config get-contexts
kubectl config use-context prod
kubectl config set-context --current --namespace=kube-system
|
get-contexts -o name 只输出名字;探活用 kubectl cluster-info 与 kubectl get --raw='/readyz'。
查看资源
1 2 3 4 5 6 7 8 9
| kubectl get pods kubectl get deploy,svc,ing
kubectl get pods -o wide
kubectl get pod web-0 -o yaml
kubectl describe pod web-0
|
-o 取值:wide、yaml、json、name、jsonpath、custom-columns。describe 末尾的 Events 段是调度失败、拉镜像失败、探针失败的第一现场。- 字段含义直接查:
kubectl explain deploy.spec.strategy.rollingUpdate。
日志与排查
1 2 3 4 5 6 7 8 9 10
| kubectl logs -f deploy/web --tail=100 kubectl logs pod/web-0 -c istio-proxy
kubectl logs pod/web-0 --previous
kubectl exec -it pod/web-0 -- sh
kubectl port-forward pod/web-0 8080:8080 kubectl port-forward svc/web 8443:https
|
-p 是 --previous 的短选项;--tail 默认 -1,表示全量。-l app=web 可跨 Pod 聚合日志,受 --max-log-requests 上限约束。port-forward 默认只监听 localhost,不经过 Service 负载均衡,也不是生产暴露方式。
创建与变更
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| kubectl apply -f deploy.yaml
kubectl create deployment web --image=nginx:1.27 --replicas=3
kubectl edit svc/web
kubectl scale deploy/web --replicas=5
kubectl rollout status deploy/web kubectl rollout history deploy/web kubectl rollout undo deploy/web --to-revision=2 kubectl rollout restart deploy/web
kubectl delete -f deploy.yaml
|
apply 维护 last-applied-configuration,与 create 混用于同一对象会产生字段归属冲突。rollout restart 只给 Pod 模板打一个重启时间戳注解,不重建 Deployment 对象。rollout history 的 CHANGE-CAUSE 默认是 <none>,需先执行 kubectl annotate deploy/web kubernetes.io/change-cause="..."。
kubectl run 与 create deployment 的区别
Kubernetes 1.18 起 kubectl run 移除了全部 generator,只创建 Pod;更早版本里 --restart=Always 生成 Deployment 的行为已经不存在。
1 2 3 4
| kubectl run debug --image=busybox:1.36 --restart=Never -- sleep 3600
kubectl create deployment web --image=nginx:1.27 --replicas=3
|
--restart 直接写进 Pod 的 restartPolicy,取值 Always / OnFailure / Never。
标签、选择器与命名空间
1 2 3 4 5 6 7 8
| kubectl get pods -l app=web,tier=frontend kubectl get pods -l 'app in (web,api)' kubectl get pods --field-selector status.phase=Pending kubectl get pods --field-selector spec.nodeName=node-1 kubectl get pods -n kube-system kubectl get pods -A kubectl label deploy/web env=prod kubectl label deploy/web env-
|
-l 是 --selector 的短选项;--field-selector 的可用字段由资源类型固定,写错时服务端返回 BadRequest;-A 会让输出多出一列 NAMESPACE。
常见报错
You must be logged in to the server (Unauthorized):凭据或 context 不对,核对 kubectl config get-contexts。pods "web" not found:多半落到了默认 default 命名空间,补 -n。unable to upgrade connection: container not found:容器还没 Running,或 -c 的容器名写错。Metrics API not available:集群缺少 metrics-server,kubectl top 不可用。
参考