Kubernetes 系列(十九)你不知道的Kubernetes CLI (kubectl)技巧
最近和一个朋友聊天,他要求我分享一个许多人都不太知道的 Kubernetes CLI(kubectl) 技巧。
实则技巧有许多,我决定在这里列举一些常用的典型的案例。每当在一台新的机器上工作时,一般做的第一件事,是设置 kubectl 的别名:
alias k=kubectl
如果你常常管理 Kubernetes ,你常常使用 kubectl 命令,所以为什么不把他设置的简短一点。
让我们一起看一下下面的提议:
1. 在 Kubernetes 资源上设置 pod 水平自动伸缩
kubectl autoscale deployment foo --min=2 --max=10
2. 基于 CronJob 创建一个 Job
kubectl create job --from=cronjob/<name of cronjob> <name of this run>
3. 查询某个账户服务权限
kubectl -n <namespace> auth can-i --list --as system:serviceaccount:<namespace>:<service account name>
4. 资源 annotation 管理
# To add annotation
kubectl annotate <resource-type>/<resource-name> foo=bar
# To remove annotation
kubectl annotate <resource-type>/<resource-name> foo-
5. 获取全部命名空间的某个资源
kubectl get [resource] -A
6. 按照时间倒序获取 events
kubectl get events --sort-by=".lastTimestamp" -n test
7. 观察所有命名空间中的所有 warnning 事件
kubectl get events -w --field-selector=type=Warning -A
8. 观察 pod 时,添加显示 event 列
kubectl get pods --watch --output-watch-events
9. 获取各种 Api 的原始 json
kubectl get --raw /apis/apps/v1
# Get metrics
kubectl get --raw /metrics
10. 等待特定的 pod 达到 ready 状态
kubectl wait --for=condition=ready pod -l foo=bar
11. 查看资源选项配置信息
kubectl explain pod.spec
12. 根据 selector 筛选某选类型资源
kubectl get deployments,replicasets,pods,services --selector=hello=yourecute
13.将 service 端口转发到本地端口
kubectl port-forward svc/<service-name> <local-port>:<remote-port>
14. 列车资源的环境变量
kubectl set env <resource>/<resource-name> --list
# 例如
kubectl set env pod/test-pod --list -n test
15. 查询pod 以及他们所在的 node 信息
kubectl get po -o=custom-columns=NODE:.spec.nodeName,NAME:.metadata.name
16. 创建 deployment 的初始YAML清单(也适用于其他资源)
kubectl create deploy nginx-deployment --image=nginx --dry-run=client -o yaml
17. 根据内存使用排序查询 pod
kubectl top pods -A --sort-by='memory'
18. 获得拥有特定标签值集的 pods 列表
kubectl get pods -l 'app in (foo,bar)'
19. 获取 pod 最后一次重启前的日志
kubectl logs <pod-name> --previous
20. 从pod 中拷贝文件到本地
kubectl cp <namespace>/<pod>:<file_path> <local_file_path>
21. 直接删除一个 pod
kubectl delete pod <pod-name> --now
22. 用特定的标签作为条件,获取对应 pod 的日志
kubectl logs -l app=xyz
23. 获取关于资源的更多信息
kubectl get <resource> -o wide
24. 更改资源,并输出变更然后执行变更
# Edit a resource and get the patch
kubectl edit <resource>/<name> --output-patch
# Use the output from the command above to apply the patch
kubectl patch --patch=<output_from_previous_command>
欢迎关注我的公众号“云原生拓展”,原创技术文章第一时间推送。
© 版权声明
文章版权归作者所有,未经允许请勿转载。




收藏了,感谢分享