k3d 使用指南
k3d 使用指南
1. k3d 简介
k3d 是一个轻量级工具,用于在 Docker 容器中快速部署和管理 k3s 集群(Rancher 的轻量级 Kubernetes 发行版)。它支持单节点或多节点集群的创建,非常适合本地开发、测试或 CI/CD 流水线中的 Kubernetes 环境模拟。
2. 安装 k3d
系统要求
- Docker:需安装 Docker(v20.10.5 及以上,runc ≥ v1.0.0-rc93)。
- kubectl:用于与 Kubernetes 集群交互。
安装方式
安装脚本(推荐):
1
2
3
4
5# 安装最新版本
curl -s https://raw.githubusercontent.com/k3d-io/k3d/main/install.sh | bash
# 安装指定版本(如 v5.0.0)
curl -s https://raw.githubusercontent.com/k3d-io/k3d/main/install.sh | TAG=v5.0.0 bash包管理器:
- Homebrew(Mac/Linux):
1
brew install k3d
- Chocolatey(Windows):
1
choco install k3d
- Arch Linux(AUR):
1
yay -S rancher-k3d-bin
- Homebrew(Mac/Linux):
3. 快速开始:创建集群
基本命令
1 | k3d cluster create <CLUSTER_NAME> |
- 示例:创建名为
mycluster的单节点集群:1
k3d cluster create mycluster
常用参数
多节点集群:
1
k3d cluster create mycluster --servers 3 --agents 2
--servers 3:创建 3 个服务器节点(控制平面)。--agents 2:创建 2 个代理节点(工作负载节点)。
端口映射:
1
k3d cluster create mycluster -p "8080:80@agent:0"
- 将宿主机的
8080端口映射到第一个代理节点的80端口。
- 将宿主机的
自定义 K3s 参数:
1
k3d cluster create mycluster --k3s-arg "--disable=traefik@server:0"
- 禁用 Traefik 组件(仅作用于第一个服务器节点)。
集成镜像仓库:
1
k3d cluster create mycluster --registry-create myregistry
- 创建一个本地镜像仓库
myregistry,并自动连接到集群。
- 创建一个本地镜像仓库
4. 集群管理
常用命令
查看集群列表:
1
k3d cluster list
启动/停止集群:
1
2k3d cluster start mycluster
k3d cluster stop mycluster删除集群:
1
k3d cluster delete mycluster
生成 kubeconfig 文件:
1
k3d cluster kubeconfig write mycluster
- 将集群配置写入
~/.kube/config,直接使用kubectl操作集群。
- 将集群配置写入
5. 高级配置
通过配置文件定义集群
创建 config.yaml 文件:1
2
3
4
5
6
7
8
9
10apiVersion: k3d.io/v1alpha4
kind: Simple
metadata:
name: mycluster
servers: 3
agents: 2
ports:
- port: 8080:80
nodeFilters:
- agent:0
运行命令:1
k3d cluster create --config config.yaml
环境变量注入
1 | k3d cluster create mycluster -e "HTTP_PROXY=http://proxy.example.com@server:0" |
- 将
HTTP_PROXY环境变量注入所有服务器节点。
GPU 直通
1 | k3d cluster create mycluster --gpus all |
- 将宿主机的所有 GPU 设备传递给集群节点。
6. 使用场景
- 本地开发:快速搭建 Kubernetes 环境,测试应用部署。
- CI/CD 流水线:在 Drone CI 或 GitHub Actions 中集成 k3d,验证多节点集群行为。
- 多节点测试:模拟生产环境中的高可用性配置。
- 教育/培训:低成本学习 Kubernetes 集群管理。
7. 卸载 k3d
1 | # 删除所有集群 |
参考链接
- 官方文档:https://k3d.io/
- GitHub 仓库:https://github.com/k3d-io/k3d
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 adong的博客!
评论









