多台云服务器的 Kubernetes 集群搭建

语言: CN / TW / HK

环境

两台或多台腾讯云服务器(本人搭建用了两台),都是 CentOs 7.6,

master 节点:服务器为 4C8G,公网 IP:124.222.61.xxx

node1节点:服务器为 4C4G,公网 IP:101.43.182.xxx

修改 hosts 信息:

在 master 节点和 node 节点的 hosts 文件中添加节点信息

$ vim /etc/hosts
124.222.61.xxx master
101.43.182.xxx node1

这里的 master 和 node1 均为 hostname,尽量不要使用默认的 hostname,修改hostname的命令为 hostnamectl set-hostname master

禁用防火墙:

$ systemctl stop firewalld
$ systemctl disable firewalld

禁用 SELINUX:

$ vim /etc/selinux/config
SELINUX=1
$ setenforce 0
$ vim /etc/selinux/config
SELINUX=disabled

加载 br_netfilter 模块:

$ modprobe br_netfilter

创建 /etc/sysctl.d/k8s.conf 文件:

net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1

执行命令使修改生效:

$ sysctl -p /etc/sysctl.d/k8s.conf

安装 ipvs:

$ cat > /etc/sysconfig/modules/ipvs.modules <<EOF
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack_ipv4
EOF
$ chmod 755 /etc/sysconfig/modules/ipvs.modules && bash /etc/sysconfig/modules/ipvs.modules && lsmod | grep -e ip_vs -e nf_conntrack_ipv4

在各个节点上都安装 ipset:

$ yum install ipset

安装管理工具 ipvsadm:

$ yum install ipvsadm

同步服务器时间:

$ yum install chrony -y
$ systemctl enable chronyd
$ systemctl start chronyd

关闭 swap 分区:

$ swapoff -a
$ vim /etc/sysctl.d/k8s.conf
(添加一行)vm.swappiness=0
$ sysctl -p /etc/sysctl.d/k8s.conf

安装 Docker:

$ yum install -y yum-utils \
  device-mapper-persistent-data \
  lvm2
$ yum-config-manager \
    --add-repo \
    http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo (阿里云镜像)
$ yum install docker-ce-18.09.9

配置 Docker 镜像加速器(阿里云):

$ mkdir -p /etc/docker
$ vim /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "registry-mirrors" : [
    "https://uvtcantv.mirror.aliyuncs.com"
  ]
}

启动 Docker:

$ systemctl start docker
$ systemctl enable docker

安装 Kubeadm:

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

然后安装 kubeadm、kubelet、kubectl:

$ yum install -y kubelet-1.16.2 kubeadm-1.16.2 kubectl-1.16.2 --disableexcludes=kubernetes

设置成开机自启动:

$ systemctl enable --now kubelet

上面的所有操作都需要在所有的节点进行配置

集群初始化

在 master 节点配置 kubeadm 初始化文件:

$ kubeadm config print init-defaults > kubeadm.yaml

修改 kubeadm.yaml 文件,修改 imageRepository ,kube-proxy 的模式为 ipvs,networking.podSubnet 设置为 10.244.0.0/16

apiVersion: kubeadm.k8s.io/v1beta2
bootstrapTokens:
- groups:
  - system:bootstrappers:kubeadm:default-node-token
  token: abcdef.0123456789abcdef
  ttl: 24h0m0s
  usages:
  - signing
  - authentication
kind: InitConfiguration
localAPIEndpoint:
  advertiseAddress: 124.222.61.xxx  # apiserver master节点IP
  bindPort: 6443
nodeRegistration:
  criSocket: /var/run/dockershim.sock
  name: master  # 默认读取当前master节点的hostname
  taints:
  - effect: NoSchedule
    key: node-role.kubernetes.io/master
---
apiServer:
  timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta2
certificatesDir: /etc/kubernetes/pki
clusterName: kubernetes
controllerManager: {}
dns:
  type: CoreDNS
etcd:
  local:
    dataDir: /var/lib/etcd
imageRepository: registry.aliyuncs.com/google_containers  # 修改成阿里云镜像源
kind: ClusterConfiguration
kubernetesVersion: v1.16.2
networking:
  dnsDomain: cluster.local
  podSubnet: 10.244.0.0/16  # Pod 网段,flannel插件需要使用这个网段
  serviceSubnet: 10.96.0.0/12
scheduler: {}
---
apiVersion: kubeproxy.config.k8s.io/v1alpha1
kind: KubeProxyConfiguration
mode: ipvs  # kube-proxy 模式

然后使用上面的配置文件进行初始化:

$ kubeadm init --config kubeadm.yaml

初始化这里有个坑,执行完上面的初始化脚本后会卡在 etcd 初始化的位置,因为 etcd 绑定端口的时候使用外网 IP,而云服务器外网 IP 并不是本机的网卡,而是网关分配的一个供外部访问的 IP,从而导致初始化进程一直重试绑定,长时间卡在这里 [kubelet-check] Initial timeout of 40s passed.

解决办法,在卡住的时候另启一个服务器终端,修改初始化生成的 etcd.yaml

vim /etc/kubernetes/manifests/etcd.yaml

将其修改成这样:

耐心等待三到四分钟就可以了。

初始化成功之后,会在终端打印一条命令,这条命令就是节点加入集群要执行的命令如下图:

拷贝 kubeconfig 文件:

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

添加节点

将 master 节点上的 $HOME/.kube/config 文件拷贝到 node 节点 $HOME/.kube/config 对应的文件中

然后执行上面 master 节点初始化生成的命令,如果忘了可以执行 kubeadm token create --print-join-command 重新获取。

kubeadm join 124.222.61.161:6443 --token 1l2un1.or6f04f1rewyf0xq     --discovery-token-ca-cert-hash sha256:1534171b93c693e6c0d7b2ed6c11bb4e2604be6d2af69a5f464ce74950ed4d9d

执行成功后运行 kubectl get nodes 命令:

$ kubectl get nodes
执行之后可以看到 status 是 NotReady 状态,因为我们还没安装网络插件

安装 flannel 网络插件:

$ wget  https://raw.githubusercontent.com/coreos/flannel/2140ac876ef134e0ed5af15c65e414cf26827915/Documentation/kube-flannel.yml
$ vi kube-flannel.yml
......
containers:
- name: kube-flannel
  image: quay.io/coreos/flannel:v0.11.0-amd64
  command:
  - /opt/bin/flanneld
  args:
  - --ip-masq
  - --kube-subnet-mgr
  - --iface=eth0  # 如果是多网卡的话,指定内网网卡的名称
......
$ kubectl apply -f kube-flannel.yml

等待一段时间查看 Pod 运行状态:

$ kubectl get pods -n kube-system
NAME                                  READY   STATUS    RESTARTS   AGE
coredns-58cc8c89f4-6nn74              1/1     Running   0          18h
coredns-58cc8c89f4-v96jb              1/1     Running   0          18h
etcd-ydzs-master                      1/1     Running   0          18h
kube-apiserver-ydzs-master            1/1     Running   2          18h
kube-controller-manager-ydzs-master   1/1     Running   0          18h
kube-flannel-ds-amd64-674zs           1/1     Running   0          18h
kube-flannel-ds-amd64-zbv7l           1/1     Running   0          18h
kube-proxy-b7c9c                      1/1     Running   0          18h
kube-proxy-bvsrr                      1/1     Running   0          18h
kube-scheduler-ydzs-master            1/1     Running   0          18h

查看 node 节点,发现也正常了:

$ kubectl get nodes
NAME     STATUS   ROLES    AGE   VERSION
master   Ready    master   18h   v1.16.2
node1    Ready    <none>   18h   v1.16.2

配置 Dashboard

$ wget https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta5/aio/deploy/recommended.yaml
$ vi recommended.yaml
# 修改Service为NodePort类型
......
kind: Service
apiVersion: v1
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kubernetes-dashboard
spec:
  ports:
    - port: 443
      targetPort: 8443
  selector:
    k8s-app: kubernetes-dashboard
  type: NodePort  # 加上type=NodePort变成NodePort类型的服务
......
$ kubectl apply -f recommended.yaml

Dashboard 会被默认安装在 kubernetes-dashboard 这个命名空间下面:

$ kubectl get pods -n kubernetes-dashboard -l k8s-app=kubernetes-dashboard
NAME                                    READY   STATUS    RESTARTS   AGE
kubernetes-dashboard-6b86b44f87-xsqft   1/1     Running   0          16h
$ kubectl get svc -n kubernetes-dashboard
NAME                        TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)         AGE
dashboard-metrics-scraper   ClusterIP   10.100.126.111   <none>        8000/TCP        17h
kubernetes-dashboard        NodePort    10.108.217.144   <none>        443:31317/TCP   17h

然后我们通过https://124.222.61.161:31317访问,会发现访问失败,因为证书过期了下面我们来生成证书:

#新建目录:
mkdir key && cd key

#生成证书
openssl genrsa -out dashboard.key 2048 

#我这里写的自己的node1节点,因为我是通过nodeport访问的;如果通过apiserver访问,可以写成自己的master节点ip
openssl req -new -out dashboard.csr -key dashboard.key -subj '/CN=124.222.61.161'
openssl x509 -req -in dashboard.csr -signkey dashboard.key -out dashboard.crt 

#删除原有的证书secret
kubectl delete secret kubernetes-dashboard-certs -n kubernetes-dashboard

#创建新的证书secret
kubectl create secret generic kubernetes-dashboard-certs --from-file=dashboard.key --from-file=dashboard.crt -n kubernetes-dashboard

#查看pod
kubectl get pod -n kubernetes-dashboard

#重启pod
kubectl delete pod kubernetes-dashboard-7b5bf5d559-gn4ls  -n kubernetes-dashboard

执行完继续访问会提示不安全连接,继续访问就好了。

这里我们使用火狐浏览器,Google 浏览器无法访问

创建用户登陆 Dashboard:

# 创建 admin.yaml 文件
$ vim admin.yaml
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: admin
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
subjects:
- kind: ServiceAccount
  name: admin
  namespace: kubernetes-dashboard

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin
  namespace: kubernetes-dashboard

# 直接创建
$ kubectl apply -f admin.yaml
$ kubectl get secret -n kubernetes-dashboard|grep admin-token
admin-token-jv2dq                  kubernetes.io/service-account-token   3      16h
kubectl get secret admin-token-jv2dq -o jsonpath={.data.token} -n kubernetes-dashboard |base64 -d
# 会生成一串很长的base64后的字符串

然后用上面的 base64 的字符串作为 token 登录 Dashboard 即可: