Kubernetes 之 Kubeadm 搭建

Kubeadm 搭建

  • 一、搭建准备
    • 1.1 环境准备
    • 1.2 所有节点安装docker
    • 1.3 所有主机安装 cri-dockerd
    • 1.4 所有节点安装kubeadm,kubelet和kubectl
    • 1.5 部署K8S集群
    • 1.6 设定kubectl
    • 1.7 部署 Dashboard

一、搭建准备

master(2C/4G,cpu核心数要求大于2)		192.168.80.10		docker、kubeadm、kubelet、kubectl、flannel
node01(2C/2G)							192.168.80.11		docker、kubeadm、kubelet、kubectl、flannel
node02(2C/2G)							192.168.80.12		docker、kubeadm、kubelet、kubectl、flannel
Harbor节点(hub.kgc.com)				192.168.80.13		docker、docker-compose、harbor-offline-v1.2.2

1.1 环境准备

//所有节点,关闭防火墙规则,关闭selinux,关闭swap交换
systemctl stop firewalld
systemctl disable firewalld
setenforce 0
sed -i 's/enforcing/disabled/' /etc/selinux/config
iptables -F && iptables -t nat -F && iptables -t mangle -F && iptables -X
swapoff -a
sed -ri 's/.*swap.*/#&/' /etc/fstab
#加载 ip_vs 模块
for i in $(ls /usr/lib/modules/$(uname -r)/kernel/net/netfilter/ipvs|grep -o "^[^.]*");do echo $i; /sbin/modinfo -F filename $i >/dev/null 2>&1 && /sbin/modprobe $i;done

//修改主机名
hostnamectl set-hostname master01
hostnamectl set-hostname node01
hostnamectl set-hostname node02

//所有节点修改hosts文件
vim /etc/hosts
192.168.80.10 master01
192.168.80.11 node01
192.168.80.12 node02

//调整内核参数
cat > /etc/sysctl.d/kubernetes.conf << EOF
#开启网桥模式,可将网桥的流量传递给iptables链
net.bridge.bridge-nf-call-ip6tables=1
net.bridge.bridge-nf-call-iptables=1
#关闭ipv6协议
net.ipv6.conf.all.disable_ipv6=1
net.ipv4.ip_forward=1
EOF

//生效参数
sysctl --system  

1.2 所有节点安装docker

yum install -y yum-utils device-mapper-persistent-data lvm2 
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 
yum install -y docker-ce docker-ce-cli containerd.io

mkdir /etc/docker
cat > /etc/docker/daemon.json <<EOF
{
  "registry-mirrors": ["https://6ijb8ubo.mirror.aliyuncs.com"],
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  }
}
EOF

#使用Systemd管理的Cgroup来进行资源控制与管理,因为相对Cgroupfs而言,Systemd限制CPU、内存等资源更加简单和成熟稳定。
#日志使用json-file格式类型存储,大小为100M,保存在/var/log/containers目录下,方便ELK等日志系统收集和管理日志。

systemctl daemon-reload
systemctl restart docker.service
systemctl enable docker.service 

docker info | grep "Cgroup Driver"
Cgroup Driver: systemd

1.3 所有主机安装 cri-dockerd

  • Kubernetes自v1.24移除了对docker-shim的支持,而Docker Engine默认又不支持CRI规范,因而二者将无法直接完成整合。 为此,Mirantis和Docker联合创建了cri-dockerd项目,用于为Docker Engine提供一个能够支持到CRI规范的垫片,从而能够让Kubernetes基于CRI控制Docker 。

  • 项目地址

https://github.com/Mirantis/cri-dockerd
cd /opt/
wget https://github.com/Mirantis/cri-dockerd/releases/download/v0.2.6/cri-dockerd-0.2.6-3.el7.x86_64.rpm

yum localinstall -y cri-dockerd-0.2.6-3.el7.x86_64.rpm

vim /lib/systemd/system/cri-docker.service
#修改ExecStart行如下
ExecStart=/usr/bin/cri-dockerd --network-plugin=cni --pod-infra-container-image=registry.aliyuncs.com/google_containers/pause:3.8

systemctl daemon-reload
systemctl enable --now cri-docker

1.4 所有节点安装kubeadm,kubelet和kubectl

//定义kubernetes源
cat > /etc/yum.repos.d/kubernetes.repo << EOF
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

yum install -y kubelet-1.25.4 kubeadm-1.25.4 kubectl-1.25.4

kubeadm version

//开机自启kubelet
systemctl enable kubelet.service

#K8S通过kubeadm安装出来以后都是以Pod方式存在,即底层是以容器方式运行,所以kubelet必须设置开机自启

1.5 部署K8S集群

//在 master01 节点上设置集群初始化配置文件
kubeadm config print init-defaults > /opt/kubeadm-config.yaml

cd /opt/
vim kubeadm-config.yaml
apiVersion: kubeadm.k8s.io/v1beta3
bootstrapTokens:
- groups:
  - system:bootstrappers:kubeadm:default-node-token
  token: abcdef.0123456789abcdef
  ttl: 24h0m0s
  usages:
  - signing
  - authentication
kind: InitConfiguration
localAPIEndpoint:
  advertiseAddress: 192.168.80.10
  bindPort: 6443
nodeRegistration:
  criSocket: unix:///var/run/cri-dockerd.sock
  imagePullPolicy: IfNotPresent
  name: master01
  taints:
  - effect: NoSchedule
    key: node-role.kubernetes.io/master
---
apiServer:
  timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta3
certificatesDir: /etc/kubernetes/pki
clusterName: kubernetes
controllerManager: {}
dns: {}
etcd:
  local:
    dataDir: /var/lib/etcd
imageRepository: registry.aliyuncs.com/google_containers
kind: ClusterConfiguration
kubernetesVersion: v1.25.4
networking:
  dnsDomain: cluster.local
  podSubnet: 10.244.0.0/16
  serviceSubnet: 10.96.0.0/16
scheduler: {}
---
apiVersion: kubeproxy.config.k8s.io/v1alpha1
kind: KubeProxyConfiguration
mode: ipvs


//查看初始化需要的镜像
kubeadm config images list --kubernetes-version 1.25.4

//所有节点拉取镜像
#拷贝yaml配置文件给其他主机,通过配置文件进行拉取镜像
for i in node01 node02; do scp /opt/kubeadm-config.yaml $i:/opt/; done

kubeadm config images pull --config /opt/kubeadm-config.yaml


//master01 节点初始化kubeadm
方法一:
kubeadm init --config=kubeadm-config.yaml --upload-certs | tee kubeadm-init.log
#--upload-certs 参数可以在后续执行加入节点时自动分发证书文件
#tee kubeadm-init.log 用以输出日志

//查看 kubeadm-init 日志
less kubeadm-init.log

//kubernetes配置文件目录
ls /etc/kubernetes/

//存放ca等证书和密码的目录
ls /etc/kubernetes/pki		


方法二:
kubeadm init \
--apiserver-advertise-address=192.168.80.10 \
--image-repository registry.aliyuncs.com/google_containers \
--kubernetes-version v1.25.4 \
--service-cidr=10.96.0.0/16 \
--pod-network-cidr=10.244.0.0/16 \
--cri-socket /var/run/cri-dockerd.sock \
--upload-certs
  • 初始化集群需使用kubeadm init命令,可以指定具体参数初始化,也可以指定配置文件初始化。
  • 可选参数:

–apiserver-advertise-address:apiserver通告给其他组件的IP地址,一般应该为Master节点的用于集群内部通信的IP地址,0.0.0.0表示节点上所有可用地址
–apiserver-bind-port:apiserver的监听端口,默认是6443
–cert-dir:通讯的ssl证书文件,默认/etc/kubernetes/pki
–control-plane-endpoint:多主节点必选项,用于指定控制平面的固定访问地址。注意:kubeadm不支持将没有–control-plane-endpoint参数的单个控制平面集群转换为高可用性集群
–image-repository:拉取镜像的镜像仓库,默认是k8s.gcr.io
–kubernetes-version:指定kubernetes版本
–pod-network-cidr:pod资源的网段,需与pod网络插件的值设置一致。Flannel网络插件的默认为10.244.0.0/16,Calico插件的默认值为192.168.0.0/16;
–service-cidr:service资源的网段
–service-dns-domain:service全域名的后缀,默认是cluster.local
–token-ttl:默认token的有效期为24小时,0表示永不过期
–cri-socket #v1.24版之后指定连接cri的socket文件路径,注意;不同的CRI连接文件不同
#如果是cRI是containerd,则使用–cri-socket unix:///run/containerd/containerd.sock
#如果是cRI是docker,则使用–cri-socket unix:///var/run/cri-dockerd.sock
#如果是CRI是CRI-o,则使用–cri-socket unix:///var/run/crio/crio.sock
#注意:CRI-o与containerd的容器管理机制不一样,所以镜像文件不能通用。

方法二初始化后需要修改 kube-proxy 的 configmap,开启 ipvs
kubectl edit cm kube-proxy -n=kube-system
修改mode: ipvs

提示:
......
Your Kubernetes control-plane has initialized successfully!

To start using your cluster, you need to run the following as a regular user:

  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config

You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
  https://kubernetes.io/docs/concepts/cluster-administration/addons/

Then you can join any number of worker nodes by running the following on each as root:

kubeadm join 192.168.80.10:6443 --token rc0kfs.a1sfe3gl4dvopck5 \
    --discovery-token-ca-cert-hash sha256:864fe553c812df2af262b406b707db68b0fd450dc08b34efb73dd5a4771d37a2

1.6 设定kubectl

  • kubectl需经由API server认证及授权后方能执行相应的管理操作,kubeadm 部署的集群为其生成了一个具有管理员权限的认证配置文件 /etc/kubernetes/admin.conf,它可由 kubectl 通过默认的 “$HOME/.kube/config” 的路径进行加载。
mkdir -p $HOME/.kube
cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
chown $(id -u):$(id -g) $HOME/.kube/config


//所有节点部署网络插件flannel
#所有节点上传 flannel 镜像 flannel.tar、flannel-cni-plugin.tar 和网络插件 cni-plugins-linux-amd64-v1.1.1.tgz 到 /opt 目录,master 节点上传 kube-flannel.yml 文件
mv /opt/cni /opt/cni_bak
mkdir -p /opt/cni/bin
tar zxvf cni-plugins-linux-amd64-v1.1.1.tgz -C /opt/cni/bin

方法一:
cd /opt
docker load < flannel.tar
docker load < flannel-cni-plugin.tar

kubectl apply -f kube-flannel.yml 


方法二:
kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml


//在 node 节点上执行 kubeadm join 命令加入群集
kubeadm join 192.168.80.10:6443 --token rc0kfs.a1sfe3gl4dvopck5 \
    --discovery-token-ca-cert-hash sha256:864fe553c812df2af262b406b707db68b0fd450dc08b34efb73dd5a4771d37a2 \
    --cri-socket /var/run/cri-dockerd.sock			#需要额外指定 cri-dockerd


//在master节点查看节点状态
kubectl get nodes
NAME       STATUS   ROLES           AGE    VERSION
master01   Ready    control-plane   88m    v1.25.4
node01     Ready    <none>          110s   v1.25.4
node02     Ready    <none>          105s   v1.25.4

kubectl get pods -A
NAMESPACE      NAME                               READY   STATUS    RESTARTS   AGE
kube-flannel   kube-flannel-ds-lc7lg              1/1     Running   0          83m
kube-flannel   kube-flannel-ds-phlnb              1/1     Running   0          88s
kube-flannel   kube-flannel-ds-wlvvk              1/1     Running   0          93s
kube-system    coredns-c676cc86f-5x7b5            1/1     Running   0          88m
kube-system    coredns-c676cc86f-8wxg7            1/1     Running   0          88m
kube-system    etcd-master01                      1/1     Running   0          88m
kube-system    kube-apiserver-master01            1/1     Running   0          88m
kube-system    kube-controller-manager-master01   1/1     Running   0          88m
kube-system    kube-proxy-rjs6g                   1/1     Running   0          88s
kube-system    kube-proxy-vp2b5                   1/1     Running   0          88m
kube-system    kube-proxy-xnllf                   1/1     Running   0          93s
kube-system    kube-scheduler-master01            1/1     Running   0          88m


//测试 pod 资源创建
kubectl create deployment nginx --image=nginx

kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP           NODE     NOMINATED NODE   READINESS GATES
nginx-554b9c67f9-zr2xs   1/1     Running   0          14m   10.244.1.2   node01   <none>           <none>

//暴露端口提供服务
kubectl expose deployment nginx --port=80 --type=NodePort

kubectl get svc
NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1      <none>        443/TCP        25h
nginx        NodePort    10.96.15.132   <none>        80:32698/TCP   4s

//测试访问
curl http://node01:32698

//扩展3个副本
kubectl scale deployment nginx --replicas=3

kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP           NODE     NOMINATED NODE   READINESS GATES
nginx-554b9c67f9-9kh4s   1/1     Running   0          66s   10.244.1.3   node01   <none>           <none>
nginx-554b9c67f9-rv77q   1/1     Running   0          66s   10.244.2.2   node02   <none>           <none>
nginx-554b9c67f9-zr2xs   1/1     Running   0          17m   10.244.1.2   node01   <none>           <none>

1.7 部署 Dashboard

kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.6.1/aio/deploy/recommended.yaml


//内核参数优化方案//
cat > /etc/sysctl.d/kubernetes.conf <<EOF
net.bridge.bridge-nf-call-iptables=1
net.bridge.bridge-nf-call-ip6tables=1
net.ipv4.ip_forward=1
net.ipv4.tcp_tw_recycle=0
vm.swappiness=0									#禁止使用 swap 空间,只有当系统内存不足(OOM)时才允许使用它
vm.overcommit_memory=1							#不检查物理内存是否够用
vm.panic_on_oom=0								#开启 OOM
fs.inotify.max_user_instances=8192
fs.inotify.max_user_watches=1048576
fs.file-max=52706963							#指定最大文件句柄数
fs.nr_open=52706963								#仅4.4以上版本支持
net.ipv6.conf.all.disable_ipv6=1
net.netfilter.nf_conntrack_max=2310720
EOF

小结:初始化失败,进行的操作

kubeadm reset -f
ipvsadm --clear 
rm -rf ~/.kube
再次进行初始化

你可能感兴趣的:(kubernetes)