Kubernetes 常用命令速查手册
目录
基础命令
kubectl 基础
# 查看 kubectl 版本
kubectl version
# 查看集群信息
kubectl cluster-info
# 查看当前上下文
kubectl config current-context
# 查看所有上下文
kubectl config get-contexts
# 切换上下文
kubectl config use-context <context-name>
# 查看集群节点
kubectl get nodes
# 查看集群节点详情
kubectl get nodes -o wide
资源创建与删除
# 创建资源
kubectl apply -f <yaml-file>
# 创建资源(指定目录下所有 yaml)
kubectl apply -f <directory>/
# 删除资源
kubectl delete -f <yaml-file>
# 删除指定类型资源
kubectl delete pod <pod-name>
kubectl delete deployment <deployment-name>
kubectl delete service <service-name>
# 强制删除 Pod
kubectl delete pod <pod-name> --force --grace-period=0
资源查看
查看各类资源
# 查看所有资源
kubectl get all
# 查看指定命名空间资源
kubectl get all -n <namespace>
# 查看所有命名空间的资源
kubectl get all --all-namespaces
kubectl get all -A
# 查看 Pod
kubectl get pods
kubectl get pods -o wide
kubectl get pods --show-labels
# 查看 Deployment
kubectl get deployments
kubectl get deploy
# 查看 Service
kubectl get services
kubectl get svc
# 查看 ConfigMap
kubectl get configmaps
kubectl get cm
# 查看 Secret
kubectl get secrets
# 查看 PersistentVolumeClaim
kubectl get pvc
# 查看 PersistentVolume
kubectl get pv
# 查看节点
kubectl get nodes
kubectl get nodes -o wide
# 查看命名空间
kubectl get namespaces
kubectl get ns
# 查看 Ingress
kubectl get ingress
kubectl get ing
# 查看事件
kubectl get events
kubectl get events --sort-by='.lastTimestamp'
查看资源详情
# 查看 Pod 详情
kubectl describe pod <pod-name>
# 查看 Deployment 详情
kubectl describe deployment <deployment-name>
# 查看 Service 详情
kubectl describe service <service-name>
# 查看节点详情
kubectl describe node <node-name>
# 查看事件详情
kubectl describe events
Pod 操作
创建和管理 Pod
# 创建 Pod
kubectl apply -f pod.yaml
# 快速创建测试 Pod
kubectl run test-pod --image=nginx --restart=Never
# 创建交互式 Pod
kubectl run -it --rm test-pod --image=busybox -- sh
# 删除 Pod
kubectl delete pod <pod-name>
# 强制删除 Pod
kubectl delete pod <pod-name> --force --grace-period=0
# 删除所有 Pod
kubectl delete pods --all
进入 Pod
# 进入 Pod 执行命令
kubectl exec -it <pod-name> -- /bin/bash
kubectl exec -it <pod-name> -- /bin/sh
# 进入指定容器
kubectl exec -it <pod-name> -c <container-name> -- /bin/bash
# 在 Pod 中执行单条命令
kubectl exec <pod-name> -- ls /app
kubectl exec <pod-name> -- cat /etc/hosts
复制文件
# 从本地复制到 Pod
kubectl cp <local-file> <pod-name>:<remote-path>
kubectl cp /root/file.txt my-pod:/tmp/file.txt
# 从 Pod 复制到本地
kubectl cp <pod-name>:<remote-path> <local-file>
kubectl cp my-pod:/tmp/file.txt /root/file.txt
# 复制目录
kubectl cp /root/dir my-pod:/tmp/dir
端口转发
# 本地端口转发到 Pod
kubectl port-forward <pod-name> <local-port>:<pod-port>
kubectl port-forward my-pod 8080:80
# 转发 Service
kubectl port-forward svc/<service-name> <local-port>:<service-port>
kubectl port-forward svc/nginx 8080:80
# 后台运行
kubectl port-forward svc/nginx 8080:80 &
Deployment 操作
创建和管理 Deployment
# 创建 Deployment
kubectl create deployment <name> --image=<image>
kubectl create deployment nginx --image=nginx
# 从 YAML 创建
kubectl apply -f deployment.yaml
# 查看 Deployment
kubectl get deployments
kubectl get deploy
# 查看 Deployment 详情
kubectl describe deployment <deployment-name>
# 删除 Deployment
kubectl delete deployment <deployment-name>
kubectl delete -f deployment.yaml
扩缩容
# 手动扩缩容
kubectl scale deployment <deployment-name> --replicas=<number>
kubectl scale deployment nginx --replicas=3
# 基于条件扩缩容
kubectl scale deployment nginx --replicas=5 --current-replicas=3
# 自动扩缩容(HPA)
kubectl autoscale deployment <deployment-name> --min=<min> --max=<max> --cpu-percent=<percent>
kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80
# 查看 HPA
kubectl get hpa
更新和回滚
# 更新镜像
kubectl set image deployment/<deployment-name> <container-name>=<new-image>
kubectl set image deployment/nginx nginx=nginx:1.19
# 查看更新状态
kubectl rollout status deployment/<deployment-name>
# 查看更新历史
kubectl rollout history deployment/<deployment-name>
# 查看指定版本详情
kubectl rollout history deployment/<deployment-name> --revision=<number>
# 回滚到上一版本
kubectl rollout undo deployment/<deployment-name>
# 回滚到指定版本
kubectl rollout undo deployment/<deployment-name> --to-revision=<number>
# 暂停更新
kubectl rollout pause deployment/<deployment-name>
# 恢复更新
kubectl rollout resume deployment/<deployment-name>
# 重启 Deployment
kubectl rollout restart deployment/<deployment-name>
编辑 Deployment
# 编辑 Deployment 配置
kubectl edit deployment <deployment-name>
# 编辑并指定编辑器
KUBE_EDITOR=nano kubectl edit deployment nginx
Service 操作
创建和管理 Service
# 创建 Service
kubectl expose deployment <deployment-name> --port=<port> --target-port=<target-port>
kubectl expose deployment nginx --port=80 --target-port=80
# 创建 NodePort 类型 Service
kubectl expose deployment nginx --port=80 --target-port=80 --type=NodePort
# 从 YAML 创建
kubectl apply -f service.yaml
# 查看 Service
kubectl get services
kubectl get svc
# 查看 Service 详情
kubectl describe service <service-name>
# 删除 Service
kubectl delete service <service-name>
Service 类型
# ClusterIP(默认)
kubectl expose deployment nginx --port=80 --target-port=80 --type=ClusterIP
# NodePort
kubectl expose deployment nginx --port=80 --target-port=80 --type=NodePort
# LoadBalancer
kubectl expose deployment nginx --port=80 --target-port=80 --type=LoadBalancer
# ExternalName
kubectl create service externalname <service-name> --external-name=<external-name>
ConfigMap 和 Secret
ConfigMap 操作
# 从字面值创建
kubectl create configmap <name> --from-literal=key1=value1 --from-literal=key2=value2
kubectl create configmap my-config --from-literal=db_host=mysql --from-literal=db_port=3306
# 从文件创建
kubectl create configmap <name> --from-file=<path>
kubectl create configmap nginx-config --from-file=nginx.conf
# 从目录创建
kubectl create configmap <name> --from-file=<directory>
# 从环境文件创建
kubectl create configmap <name> --from-env-file=<env-file>
# 查看 ConfigMap
kubectl get configmaps
kubectl get cm
# 查看 ConfigMap 详情
kubectl describe configmap <name>
# 编辑 ConfigMap
kubectl edit configmap <name>
# 删除 ConfigMap
kubectl delete configmap <name>
Secret 操作
# 创建 Secret(通用)
kubectl create secret generic <name> --from-literal=key1=value1
kubectl create secret generic db-secret --from-literal=password=123456
# 从文件创建
kubectl create secret generic <name> --from-file=<path>
# 创建 docker registry secret
kubectl create secret docker-registry <name> \
--docker-server=<server> \
--docker-username=<username> \
--docker-password=<password> \
--docker-email=<email>
kubectl create secret docker-registry regcred \
--docker-server=registry.example.com \
--docker-username=admin \
--docker-password=password \
--docker-email=admin@example.com
# 创建 TLS secret
kubectl create secret tls <name> --cert=<path-to-cert> --key=<path-to-key>
# 查看 Secret
kubectl get secrets
# 查看 Secret 详情(内容已编码)
kubectl describe secret <name>
# 查看 Secret 内容(解码)
kubectl get secret <name> -o jsonpath='{.data.key1}' | base64 -d
# 删除 Secret
kubectl delete secret <name>
持久卷操作
PersistentVolumeClaim
# 创建 PVC
kubectl apply -f pvc.yaml
# 查看 PVC
kubectl get pvc
# 查看 PVC 详情
kubectl describe pvc <pvc-name>
# 删除 PVC
kubectl delete pvc <pvc-name>
PersistentVolume
# 查看 PV
kubectl get pv
# 查看 PV 详情
kubectl describe pv <pv-name>
# 删除 PV
kubectl delete pv <pv-name>
StorageClass
# 查看 StorageClass
kubectl get storageclass
kubectl get sc
# 查看默认 StorageClass
kubectl get storageclass -o jsonpath='{.items[?(@.metadata.annotations.storageclass\.kubernetes\.io/is-default-class=="true")].metadata.name}'
# 设置默认 StorageClass
kubectl annotate storageclass <sc-name> storageclass.kubernetes.io/is-default-class=true
日志与调试
查看日志
# 查看 Pod 日志
kubectl logs <pod-name>
# 实时查看日志
kubectl logs -f <pod-name>
# 查看最后 N 行日志
kubectl logs --tail=100 <pod-name>
# 查看指定时间以来的日志
kubectl logs --since=1h <pod-name>
kubectl logs --since-time=2024-01-01T00:00:00Z <pod-name>
# 查看指定容器日志
kubectl logs <pod-name> -c <container-name>
# 查看前一个容器的日志(容器重启后)
kubectl logs <pod-name> --previous
# 查看所有容器日志
kubectl logs <pod-name> --all-containers
# 将日志输出到文件
kubectl logs <pod-name> > pod.log
调试命令
# 查看 Pod 事件
kubectl describe pod <pod-name>
# 查看集群事件
kubectl get events --sort-by='.lastTimestamp'
# 查看指定命名空间事件
kubectl get events -n <namespace>
# 查看 Pod 资源使用
kubectl top pod <pod-name>
# 查看节点资源使用
kubectl top nodes
# 查看 Pod 资源请求和限制
kubectl describe pod <pod-name> | grep -A 5 "Limits\|Requests"
调试 Pod
# 创建调试 Pod
kubectl run -it --rm debug --image=busybox -- sh
# 创建调试 Pod(带网络工具)
kubectl run -it --rm debug --image=nicolaka/netshoot -- bash
# 测试 DNS 解析
kubectl run -it --rm debug --image=busybox -- nslookup kubernetes
# 测试服务连通性
kubectl run -it --rm debug --image=busybox -- nc -zv <service-name> <port>
kubectl run -it --rm debug --image=busybox -- wget -qO- http://<service-name>:<port>
# 测试外部连接
kubectl run -it --rm debug --image=busybox -- ping google.com
kubectl run -it --rm debug --image=curlimages/curl -- curl -v http://example.com
网络相关
网络策略
# 查看网络策略
kubectl get networkpolicies
kubectl get netpol
# 查看网络策略详情
kubectl describe networkpolicy <name>
# 创建网络策略
kubectl apply -f networkpolicy.yaml
DNS 相关
# 查看 CoreDNS
kubectl get pods -n kube-system -l k8s-app=kube-dns
# 查看 CoreDNS 配置
kubectl get configmap coredns -n kube-system -o yaml
# 测试 DNS
kubectl run -it --rm debug --image=busybox -- nslookup kubernetes
kubectl run -it --rm debug --image=busybox -- nslookup <service-name>.<namespace>.svc.cluster.local
Ingress
# 查看 Ingress
kubectl get ingress
kubectl get ing
# 查看 Ingress 详情
kubectl describe ingress <name>
# 创建 Ingress
kubectl apply -f ingress.yaml
# 删除 Ingress
kubectl delete ingress <name>
节点管理
节点状态
# 查看节点
kubectl get nodes
# 查看节点详情
kubectl get nodes -o wide
# 查看节点详情
kubectl describe node <node-name>
# 查看节点资源使用
kubectl top nodes
# 查看节点标签
kubectl get nodes --show-labels
节点标签和污点
# 添加标签
kubectl label node <node-name> key=value
kubectl label node node-1 env=prod
# 删除标签
kubectl label node <node-name> key-
kubectl label node node-1 env-
# 查看标签
kubectl get nodes --show-labels
# 添加污点
kubectl taint node <node-name> key=value:NoSchedule
kubectl taint node node-1 dedicated=gpu:NoSchedule
# 删除污点
kubectl taint node <node-name> key:NoSchedule-
kubectl taint node node-1 dedicated:NoSchedule-
# 查看污点
kubectl describe node <node-name> | grep Taints
节点调度
# 停止调度(标记为不可调度)
kubectl cordon <node-name>
# 恢复调度
kubectl uncordon <node-name>
# 驱逐节点上的 Pod
kubectl drain <node-name>
# 强制驱逐(忽略 DaemonSet 和未管理的 Pod)
kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data --force
# 删除节点
kubectl delete node <node-name>
命名空间操作
# 查看命名空间
kubectl get namespaces
kubectl get ns
# 创建命名空间
kubectl create namespace <name>
kubectl create ns my-namespace
# 从 YAML 创建
kubectl apply -f namespace.yaml
# 删除命名空间
kubectl delete namespace <name>
# 在指定命名空间执行命令
kubectl get pods -n <namespace>
# 设置默认命名空间
kubectl config set-context --current --namespace=<namespace>
# 查看当前默认命名空间
kubectl config view --minify | grep namespace
配置管理
kubeconfig
# 查看 kubeconfig
kubectl config view
# 查看当前上下文
kubectl config current-context
# 查看所有上下文
kubectl config get-contexts
# 切换上下文
kubectl config use-context <context-name>
# 设置默认命名空间
kubectl config set-context --current --namespace=<namespace>
# 添加集群配置
kubectl config set-cluster <cluster-name> --server=<server-url> --certificate-authority=<ca-file>
# 添加用户配置
kubectl config set-credentials <user-name> --client-certificate=<cert-file> --client-key=<key-file>
# 添加上下文
kubectl config set-context <context-name> --cluster=<cluster-name> --user=<user-name> --namespace=<namespace>
# 删除上下文
kubectl config delete-context <context-name>
# 删除集群
kubectl config delete-cluster <cluster-name>
# 删除用户
kubectl config unset users.<user-name>
实用技巧
格式化输出
# JSON 格式
kubectl get pods -o json
# YAML 格式
kubectl get pods -o yaml
# 宽格式(显示更多信息)
kubectl get pods -o wide
# 自定义列
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase
# 仅显示名称
kubectl get pods -o name
# 显示标签
kubectl get pods --show-labels
# 按标签过滤
kubectl get pods -l app=nginx
kubectl get pods -l 'app in (nginx,redis)'
快捷别名
# 添加到 ~/.bashrc 或 ~/.zshrc
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kdel='kubectl delete'
alias ka='kubectl apply -f'
alias kl='kubectl logs'
alias ke='kubectl exec -it'
alias kpf='kubectl port-forward'
# 缩写
kubectl get po # pod
kubectl get svc # service
kubectl get deploy # deployment
kubectl get cm # configmap
kubectl get ns # namespace
kubectl get ing # ingress
kubectl get pvc # persistentvolumeclaim
kubectl get pv # persistentvolume
kubectl get sa # serviceaccount
批量操作
# 删除所有 Evicted 状态的 Pod
kubectl get pods --all-namespaces --field-selector=status.phase=Failed -o json | kubectl delete -f -
# 删除指定标签的所有 Pod
kubectl delete pods -l app=nginx
# 批量重启 Deployment
kubectl rollout restart deployment -l app=nginx
# 批量查看多个资源
kubectl get pods,svc,deploy
Pod 故障排查命令
查看 Pod 状态
# 查看所有 Pod 状态
kubectl get pods -n <namespace>
# 查看 Pod 详细状态
kubectl get pods -n <namespace> -o wide
# 查看特定 Pod
kubectl get pod <pod-name> -n <namespace>
查看 Pod 失败原因
# 查看 Pod 详情(包含事件)
kubectl describe pod <pod-name> -n <namespace>
# 示例:查看 MySQL Pod 失败原因
kubectl describe pod data-collection-mysql-549fc85557-4hzpr -n data-collection
# 只查看最后 20 行(快速定位问题)
kubectl describe pod <pod-name> -n <namespace> | tail -20
查看事件
# 查看命名空间所有事件
kubectl get events -n <namespace>
# 按时间排序查看事件
kubectl get events -n <namespace> --sort-by='.lastTimestamp'
# 查看所有命名空间事件
kubectl get events -A
# 持续监控事件
kubectl get events -n <namespace> --watch
查看 PVC 状态
# 查看 PVC 状态(Pending 常见原因)
kubectl get pvc -n <namespace>
# 查看 PVC 详情
kubectl describe pvc <pvc-name> -n <namespace>
# 示例
kubectl get pvc -n data-collection
kubectl describe pvc mysql-pvc -n data-collection
查看节点状态
# 查看节点状态
kubectl get nodes
# 查看节点详情
kubectl describe node <node-name>
# 查看节点资源使用
kubectl top nodes
# 查看节点标签
kubectl get nodes --show-labels
Pod Pending 常见原因
| 原因 |
排查命令 |
解决方案 |
| PVC 未绑定 |
kubectl get pvc -n <ns> |
检查 StorageClass 是否存在 |
| 存储类不存在 |
kubectl get storageclass |
创建 StorageClass 或修改配置 |
| 节点资源不足 |
kubectl describe node <node> |
释放资源或添加节点 |
| 节点选择器不匹配 |
kubectl get nodes --show-labels |
添加节点标签或修改 Pod 配置 |
| 污点/容忍问题 |
`kubectl describe node |
grep Taints` |
快速诊断脚本
# 一键诊断 Pod 问题
#!/bin/bash
NAMESPACE="data-collection"
POD_NAME="data-collection-mysql-549fc85557-4hzpr"
echo "=== Pod Status ==="
kubectl get pod $POD_NAME -n $NAMESPACE -o wide
echo -e "\n=== Pod Events ==="
kubectl describe pod $POD_NAME -n $NAMESPACE | grep -A 20 "Events:"
echo -e "\n=== PVC Status ==="
kubectl get pvc -n $NAMESPACE
echo -e "\n=== Node Status ==="
kubectl get nodes
echo -e "\n=== Recent Events ==="
kubectl get events -n $NAMESPACE --sort-by='.lastTimestamp' | tail -10
常见问题排查
Pod 一直处于 Pending 状态
# 查看 Pod 事件
kubectl describe pod <pod-name>
# 常见原因:
# 1. 资源不足:节点 CPU/内存不足
# 2. PVC 未绑定:存储卷问题
# 3. 节点选择器不匹配:标签问题
# 4. 污点/容忍:节点污点问题
Pod 一直处于 CrashLoopBackOff
# 查看日志
kubectl logs <pod-name>
kubectl logs <pod-name> --previous
# 查看事件
kubectl describe pod <pod-name>
# 常见原因:
# 1. 容器进程崩溃
# 2. 健康检查失败
# 3. 配置错误
# 4. 资源限制
Pod 无法解析 DNS
# 检查 CoreDNS
kubectl get pods -n kube-system -l k8s-app=kube-dns
# 检查 CoreDNS 日志
kubectl logs -n kube-system <coredns-pod>
# 测试 DNS
kubectl run -it --rm debug --image=busybox -- nslookup kubernetes
Service 无法访问
# 检查 Service 端点
kubectl get endpoints <service-name>
# 检查 Pod 标签
kubectl get pods --show-labels
# 检查 Service 选择器
kubectl describe service <service-name>
# 测试服务连通性
kubectl run -it --rm debug --image=busybox -- nc -zv <service-name> <port>
PVC 无法绑定
# 检查 PVC 状态
kubectl describe pvc <pvc-name>
# 检查 PV
kubectl get pv
# 检查 StorageClass
kubectl get storageclass
# 常见原因:
# 1. StorageClass 不存在
# 2. 存储配额不足
# 3. PV 大小不匹配
StorageClass 问题排查
问题现象
# Pod 一直处于 Pending 状态
kubectl get pods -n data-collection
NAME READY STATUS RESTARTS AGE
data-collection-backend-5df6f9bc68-gdx5p 0/1 Pending 0 16m
data-collection-mysql-549fc85557-4hzpr 0/1 Pending 0 16m
# 事件显示 StorageClass 不存在
kubectl get events -n data-collection
Warning ProvisioningFailed persistentvolumeclaim/mysql-pvc storageclass.storage.k8s.io "standard" not found
Warning FailedScheduling pod/data-collection-mysql pod has unbound immediate PersistentVolumeClaims
排查步骤
# 1. 查看 Pod 状态
kubectl get pods -n data-collection
# 2. 查看事件
kubectl get events -n data-collection --sort-by='.lastTimestamp'
# 3. 查看 PVC 状态
kubectl get pvc -n data-collection
# 4. 查看 StorageClass(关键)
kubectl get storageclass
kubectl get sc
# 5. 查看 PVC 详情
kubectl describe pvc mysql-pvc -n data-collection
解决方案
方案1:查看并使用已有的 StorageClass
# 查看已有 StorageClass
kubectl get sc
# 输出示例:
# NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE
# local-path rancher.io/local-path Delete WaitForFirstConsumer
# longhorn driver.longhorn.io Delete Immediate
# 修改 PVC 配置使用已有的 StorageClass
# 将 storageClassName: standard 改为 storageClassName: local-path
方案2:创建 StorageClass "standard"
# 创建 StorageClass 配置文件
cat > standard-storageclass.yaml << 'EOF'
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: standard
annotations:
storageclass.kubernetes.io/is-default-class: "true"
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
EOF
# 应用配置
kubectl apply -f standard-storageclass.yaml
# 验证创建成功
kubectl get sc
方案3:创建 Local Path Provisioner StorageClass
# 使用 local-path-provisioner(推荐)
# 下载并安装
kubectl apply -f https://raw.githubusercontent.com/rancher/local-path-provisioner/v0.0.24/deploy/local-path-storage.yaml
# 查看创建的 StorageClass
kubectl get sc
# 修改 PVC 使用 local-path
# storageClassName: local-path
方案4:使用 hostPath(仅测试环境)
# 修改 Deployment,不使用 PVC,直接使用 hostPath
volumes:
- name: mysql-data
hostPath:
path: /data/mysql
type: DirectoryOrCreate
重新部署
# 1. 删除现有部署
kubectl delete -f all-in-one.yaml
# 2. 修改配置文件中的 storageClassName
# storageClassName: standard -> storageClassName: <已有的StorageClass名称>
# 3. 重新部署
kubectl apply -f all-in-one.yaml
# 4. 验证 Pod 状态
kubectl get pods -n data-collection
# 5. 验证 PVC 状态
kubectl get pvc -n data-collection
StorageClass 类型对照
快速诊断脚本
#!/bin/bash
echo "=== StorageClass 列表 ==="
kubectl get sc
echo -e "\n=== PVC 状态 ==="
kubectl get pvc -A
echo -e "\n=== Pending 状态的 Pod ==="
kubectl get pods -A | grep Pending
echo -e "\n=== ProvisioningFailed 事件 ==="
kubectl get events -A | grep ProvisioningFailed
参考资料