使用 kind 搭建 k8s 开发环境

Kind(Kubernetes in Docker) 是一个 Kubernetes 孵化项目,Kind 是一套开箱即用的 Kubernetes 环境搭建方案。顾名思义,就是将 Kubernetes 所需要的所有组件,全部部署在一个 Docker 容器中,可以很方便的搭建 Kubernetes 集群。

安装 docker

安装教程

安装 kubectl

# 安装依赖
apt install apt-transport-https ca-certificates -y

# 编辑镜像源文件,文件末尾加入阿里云k8s镜像源配置
echo 'deb https://mirrors.aliyun.com/kubernetes/apt kubernetes-xenial main' >> /etc/apt/sources.list
#更新证书
curl https://mirrors.aliyun.com/kubernetes/apt/doc/apt-key.gpg | sudo apt-key add
#更新源
apt update

apt-get install -y kubectl

配置kubectl自动补全(可选)

apt install bash-completion -y
cat << EOF >> ~/.profile
alias k='kubectl'
source <(kubectl completion bash)
complete -F __start_kubectl k
EOF

source ~/.profile

安装 Kind

# For AMD64 / x86_64
[ $(uname -m) = x86_64 ] && curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.26.0/kind-linux-amd64
# For ARM64
[ $(uname -m) = aarch64 ] && curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.26.0/kind-linux-arm64
chmod +x ./kind
sudo mv ./kind /usr/local/bin/kind

使用 kind 创建集群

新建文件cluster.yaml 内容如下

vim cluster.yaml

kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
  extraPortMappings:
  - containerPort: 31000  # 将主机 31000 端口映射到容器的 31000 端口
    hostPort: 31000
    listenAddress: "0.0.0.0" # Optional, defaults to "0.0.0.0"
    protocol: tcp # Optional, defaults to tcp
- role: worker
- role: worker
- role: worker

安装脚本

# 安装
kind create cluster --config cluster.yaml --name myk8s

# 更换 context
kubectl cluster-info --context kind-myk8s

创建 service

# 创建一个 nginx 的 deploy 测试服务
k create deploy nginx --image=nginx

# 冗余部署实现高可用
k scale deployment nginx --replicas 3

# 暴露服务
k expose deployment nginx --name nginx --port=80 --target-port=80 --type=NodePort

# 修改 NodePort 端口为 31000 让主机能够访问
k edit deployment nginx
......
  ports:
  - nodePort: 31000  # 修改
    port: 80
    protocol: TCP
    targetPort: 80
....

k get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP        6m5s
nginx        NodePort    10.96.91.4   <none>        80:31000/TCP   3m7s

浏览器输入ip:31000 大功告成