trx
Published on 2024-07-04 / 34 Visits
0

Kubernetes命令行工具

基础命令

资源查看

# 查看资源(支持跨命名空间)

kubectl get pods -A              # 所有命名空间的Pod

kubectl get svc -n <namespace>   # 指定命名空间的Service

kubectl get deployments --all-namespaces  # 所有部署

# 带自定义列输出

kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName

# 查看资源详情(JSON/YAML格式)

kubectl get pod <pod-name> -o json

kubectl get deployment <deploy-name> -o yaml

日志与调试

# 实时日志跟踪

kubectl logs -f <pod-name> --since=1h  # 跟踪最近1小时的日志

kubectl logs -f <pod-name> -c <container-name>  # 多容器Pod指定容器

# 查看容器上次启动日志

kubectl logs --previous <pod-name>

资源操作

# 创建资源(不通过YAML)

kubectl create deployment <name> --image=nginx:latest

kubectl expose deployment <name> --port=80 --type=NodePort

# 删除资源(支持标签筛选)

kubectl delete pod --selector app=myapp

kubectl delete all --all -n <namespace>  # 删除命名空间所有资源

#### 容器交互

# 带调试容器进入

kubectl debug -it <pod-name> --image=busybox --target=<container-name>

kubectl exec <pod-name> -- env        # 查看容器环境变量

状态诊断

kubectl describe node <node-name>      # 节点详细信息(含资源分配)

kubectl get events --sort-by='.metadata.creationTimestamp'  # 按时间排序事件

kubectl get events --field-selector involvedObject.kind=Pod  # 筛选Pod事件

---

进阶命令

配置管理

# 动态编辑资源

kubectl edit configmap <cm-name>       # 直接修改ConfigMap

kubectl annotate pod <pod-name> key=value  # 添加注解

# 资源差异比较

kubectl diff -f deployment.yaml        # 对比集群状态与文件差异

滚动更新

# 滚动更新管理

kubectl rollout history deployment/<name>  # 查看更新历史

kubectl rollout undo deployment/<name> --to-revision=2  # 回滚到指定版本

kubectl set image deployment/<name> nginx=nginx:1.20  # 直接更新镜像

#### 资源调度

# 节点维护操作

kubectl taint nodes <node> dedicated=special:NoSchedule  # 添加污点

kubectl drain <node> --delete-emptydir-data --force       # 强制排空节点

网络调试

# 高级网络诊断

kubectl port-forward service/<svc-name> 8080:80 --address=0.0.0.0  # 暴露到外部

kubectl run curl-test --image=curlimages/curl --rm -it -- curl http://service:port

资源监控

# 实时资源监控

kubectl top pod --sort-by=cpu          # 按CPU排序

kubectl top node --show-capacity       # 显示节点容量

---

高级调试与运维

资源分析

# 查看Pod调度失败原因

kubectl get pods -o wide --field-selector spec.nodeName=""

# 检查资源配额

kubectl describe quota -n <namespace>

# 查看Finalizers阻塞删除

kubectl get <resource> -o jsonpath='{.items[*].metadata.finalizers}'

批量操作

# 跨命名空间批量操作

kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' | xargs -I{} kubectl exec {} -- echo hello

# 清理Evicted Pods

kubectl delete pods --field-selector status.phase=Evicted

安全审计

# RBAC检查

kubectl auth can-i create deployments

kubectl auth can-i delete pods --as=system:serviceaccount:<ns>:<sa>

# 查看证书信息

kubectl config view --raw -o jsonpath='{.clusters[0].cluster.certificate-authority-data}' | base64 -d | openssl x509 -text

---

实用技巧补充

1. 快速上下文切换

kubectl config use-context <cluster-name>

kubectl config set-context --current --namespace=<ns>  # 设置默认命名空间

2. 资源模板生成

kubectl create deployment myapp --image=nginx --dry-run=client -o yaml > deploy.yaml

kubectl explain deployment.spec.template.spec.containers  # 查看字段说明

3. 自定义输出格式

kubectl get pods -o jsonpath='{range .items[*]}{.status.podIP}{"\t"}{.metadata.name}{"\n"}{end}'

kubectl get nodes -o jsonpath='{.items[*].metadata.labels}' | jq .  # 需要jq工具

4. 故障排查工具箱

# 临时调试Pod

kubectl run debug-shell --rm -i --tty --image nicolaka/netshoot -- /bin/bash

# 网络连通性测试

kubectl exec <pod> -- curl -v http://service.namespace.svc.cluster.local

5. 资源回收策略

# 清理未运行的资源

kubectl delete all --selector app=unused --grace-period=0 --force

kubectl delete jobs --field-selector status.successful=1  # 清理完成Job

---

命令速查表

| 类别 | 常用命令 |

|------------|--------------------------------------------------------------------------|

| 排错 | kubectl describe, kubectl logs --previous, kubectl get events |

| 网络 | kubectl port-forward, kubectl expose, kubectl run curl-test |

| 调度 | kubectl cordon, kubectl taint, kubectl top |

| 配置 | kubectl kustomize, kubectl diff, kubectl apply --server-side |

| 安全 | kubectl auth can-i, kubectl certificate approve, kubectl get role |

| 扩展 | kubectl get crd, kubectl get <custom-resource> |

---

注意事项

1. 生产环境慎用 --force--grace-period=0

2. 优先使用 kubectl apply 而非 create 以保持声明式管理

3. 使用 --dry-run=client 验证YAML文件语法

4. 重要操作前执行 kubectl diff 确认变更内容

5. 复杂查询推荐搭配 jqyq 工具处理输出