kubectl config
管理 kubeconfig 文件,切换集群和上下文
语法
kubectl config <subcommand> [flags]
参数
| 参数 | 说明 | 示例 | 级别 |
|---|---|---|---|
get-contexts |
列出所有可用上下文 | kubectl config get-contexts |
常用 |
current-context |
显示当前使用的上下文 | kubectl config current-context |
常用 |
use-context |
切换到指定上下文 | kubectl config use-context production |
常用 |
set-context |
修改上下文配置 | kubectl config set-context --current --namespace=dev |
进阶 |
view |
查看 kubeconfig 内容 | kubectl config view --minify |
常用 |
示例
查看所有上下文
kubectl config get-contexts
带 * 号的是当前活跃上下文
切换集群
kubectl config use-context production-cluster
切换到生产集群
设置默认命名空间
kubectl config set-context --current --namespace=my-app
避免每次都加 -n 参数
查看当前配置
kubectl config view --minify
--minify 只显示当前上下文的配置
删除上下文
kubectl config delete-context old-cluster
清理不再使用的集群配置
常见错误
context not found
用 get-contexts 确认上下文名称是否正确
unable to connect to the server
集群不可达,检查网络或 VPN 连接
技巧
- 用 kubectx 工具可以更快速地切换上下文
- 设置默认命名空间避免误操作 default 命名空间
- 多集群管理时给上下文起有意义的名字