kubernetes 二进制多master部署 v-1.18.6

Posted X糊涂仙儿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了kubernetes 二进制多master部署 v-1.18.6相关的知识,希望对你有一定的参考价值。

一、环境准备

本环境是由单独的etcd集群(3节点)及双master双node节点:

1、k8s环境

#主机名ip
192.168.1.31 km01
192.168.1.32 km02
192.168.1.81 node01
192.168.1.82 node02
#目录
/opt/kubernetes/ssl,cfg,logs,bin

2、etcd环境

1> etcd集群信息

# 主机名,ip
192.168.1.61 etcd-01 
192.168.1.62 etcd-02 
192.168.1.63 etcd-03
# 目录
/opt/etcd/cfg,ssl

2> etcd集群搭建

https://blog.51cto.com/keep11/3651290

3> etcd目录
```html/xml
[root@k01 ~]# cd /opt/etcd/
[root@k01 etcd]# tree ./
./
├── bin
│   ├── cfssl
│   └── cfssljson
├── cfg
│   └── etcd.conf
└── ssl
├── ca-key.pem
├── ca.pem
├── server-key.pem
└── server.pem

4> etcd集群状态
```html/xml
[root@k01 ~]# etcdctl --cacert=/opt/etcd/ssl/ca.pem --cert=/opt/etcd/ssl/server.pem --key=/opt/etcd/ssl/server-key.pem --endpoints="https://192.168.1.61:2379,https://192.168.1.62:2379,https://192.168.1.63:2379" endpoint health
https://192.168.1.62:2379 is healthy: successfully committed proposal: took = 95.324662ms
https://192.168.1.61:2379 is healthy: successfully committed proposal: took = 94.795766ms
https://192.168.1.63:2379 is healthy: successfully committed proposal: took = 96.143882ms

二、master部署

2.1 生成证书

kubernetes 组件需要使用x509证书对通信进行加密和认证,创建一套CA自签名根证书。
创建的CA为私有内部认证中心,认证中心也需要一个CA证书和相应的CA私钥,CA私钥需要妥善保管,拥有私钥可以欺骗CA颁发证书。

2.1.1 创建CA根证书

```html/xml
[root@km01 k8sssl]# mkdir -p /root/k8sssl && cd /root/k8sssl

CA证书集群共享,只需一个,后续创建证书子CA证书根据config的profile生成

[root@km01 k8sssl]# cat > ca-config.json << EOF
{
"signing": {
"default": {
"expiry": "87600h"
},
"profiles": {
"kubernetes": {
"expiry": "87600h",
"usages": [
"signing",
"key encipherment",
"server auth",
"client auth"
]
}
}
}
}
EOF

创建根CA证书签名请求文件

cat > ca-csr.json << EOF
{
"CN": "kubernetes",
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"L": "Beijing",
"ST": "Beijing",
"O": "k8s",
"OU": "System"
}
]
}
EOF

#### 2.1.2 生成CA证书(ca.pem)和密钥(ca-key.pem)

cfssl gencert -initca ca-csr.json | cfssljson -bare ca -
[root@km01 k8sssl]# ls ca*
ca-config.json ca.csr ca-csr.json ca-key.pem ca.pem

### 2.2 部署kube-apiserver组件
1> 使用CA签发kube-apiserver https证书

[root@km01 k8sssl]# cat server-csr.json
{
"CN": "kubernetes",
"hosts": [
"10.0.0.1",
"127.0.0.1",
"192.168.1.31",
"192.168.1.32",
"192.168.1.33", //ip预留用于扩展,master-ip、LB-ip、VIP
"192.168.1.30",
"192.168.1.34",
"kubernetes",
"kubernetes.default",
"kubernetes.default.svc",
"kubernetes.default.svc.cluster",
"kubernetes.default.svc.cluster.local"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"L": "BeiJing",
"ST": "BeiJing",
"O": "k8s",
"OU": "System"
}
]
}


2> 解压拷贝

[root@km01 k8sssl]# mkdir -p /opt/kubernetes/{bin,cfg,ssl,logs}
[root@km01 k8sssl]# tar xzvf kubernetes-server-linux-amd64-1.18.6.tar.gz
[root@km01 k8sssl]# cd /root/kuberneters/server/bin/ && cp kube-apiserver kube-sheduler kube-controller-manager /opt/kubernetes/bin && cp kubectl /usr/local/bin

3> 创建kube-apiserver.conf

[root@km01 k8sssl]# cat > /opt/kubernetes/cfg/kube-apiserver.conf << EOF
KUBE_APISERVER_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/kubernetes/logs \\
--etcd-servers=https://192.168.1.61:2379,https://192.168.1.62:2379,https://192.168.1.63:2379 \\
--bind-address=192.168.1.31 \\
--secure-port=6443 \\
--advertise-address=192.168.1.31 \\
--allow-privileged=true \\
--service-cluster-ip-range=10.0.0.0/24 \\
--enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,ResourceQuota,NodeRestriction \\
--authorization-mode=RBAC,Node \\
--enable-bootstrap-token-auth=true \\
--token-auth-file=/opt/kubernetes/cfg/token.csv \\
--service-node-port-range=30000-32767 \\
--kubelet-client-certificate=/opt/kubernetes/ssl/server.pem \\
--kubelet-client-key=/opt/kubernetes/ssl/server-key.pem \\
--tls-cert-file=/opt/kubernetes/ssl/server.pem \\
--tls-private-key-file=/opt/kubernetes/ssl/server-key.pem \\
--client-ca-file=/opt/kubernetes/ssl/ca.pem \\
--service-account-key-file=/opt/kubernetes/ssl/ca-key.pem \\
--service-account-issuer=api \\
--service-account-signing-key-file=/opt/kubernetes/ssl/server-key.pem \\
--etcd-cafile=/opt/etcd/ssl/ca.pem \\
--etcd-certfile=/opt/etcd/ssl/server.pem \\
--etcd-keyfile=/opt/etcd/ssl/server-key.pem \\
--requestheader-client-ca-file=/opt/kubernetes/ssl/ca.pem \\
--proxy-client-cert-file=/opt/kubernetes/ssl/server.pem \\
--proxy-client-key-file=/opt/kubernetes/ssl/server-key.pem \\
--requestheader-allowed-names=kubernetes \\
--requestheader-extra-headers-prefix=X-Remote-Extra- \\
--requestheader-group-headers=X-Remote-Group \\
--requestheader-username-headers=X-Remote-User \\
--enable-aggregator-routing=true \\
--audit-log-maxage=30 \\
--audit-log-maxbackup=3 \\
--audit-log-maxsize=100 \\
--audit-log-path=/opt/kubernetes/logs/k8s-audit.log"
EOF

```html/xml
注:上面两个\\ \\ 第一个是转义符,第二个是换行符,使用转义符是为了使用EOF保留换行符
参数说明:
--logtostderr:启用日志
--v:日志等级
--log-dir:日志目录
--etcd-servers:etcd集群地址
--bind-address:监听地址
--secure-port:https安全端口
--advertise-address:集群通告地址
--allow-privileged:启用授权
--service-cluster-ip-range:Service虚拟IP地址段
--enable-admission-plugins:准入控制模块
--authorization-mode:认证授权,启用RBAC授权和节点自管理
--enable-bootstrap-token-auth:启用TLS bootstrap机制
--token-auth-file:bootstrap token文件
--service-node-port-range:Service nodeport类型默认分配端口范围
--kubelet-client-xxx:apiserver访问kubelet客户端证书
--tls-xxx-file:apiserver https证书
1.20版本必须加的参数:--service-account-issuer,--service-account-signing-key-file
--etcd-xxxfile:连接Etcd集群证书
--audit-log-xxx:审计日志
启动聚合层相关配置:--requestheader-client-ca-file,--proxy-client-cert-file,--proxy-client-key-file,--requestheader-allowed-names,--requestheader-extra-headers-prefix,--requestheader-group-headers,--requestheader-username-headers,--enable-aggregator-routing

4> 拷贝kube-apiserver所需的证书
拷贝证书到kube-apiserver认证目录,将etcd(192.168.1.61) 中的ssl证书拷贝至k8s(192.168.1.31)的/opt/etcd/ssl
```html/xml

k8s证书拷贝

cp /root/k8sssl/ca*pem /opt/kubernetes/ssl/

etcd证书拷贝

mkdir -p /opt/etcd/
scp root@192.168.1.61:/opt/etcd/ssl/ /opt/etcd/

生成kube-apiserver中使用的token.csv文件

cat > /opt/kubernetes/cfg/token.csv << EOF
5787e762eca4453de8bfb2f8f52733c3,kubelet-bootstrap,10001,"system:node-bootstrapper"
EOF

重新生成替换

head -c 16 /dev/urandom | od -An -t x | tr -d \' \'

5> systemd管理api-server、开机启动

cat > /usr/lib/systemd/system/kube-apiserver.service << EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/kubernetes/kubernetes

[Service]
EnvironmentFile=/opt/kubernetes/cfg/kube-apiserver.conf
ExecStart=/opt/kubernetes/bin/kube-apiserver \\$KUBE_APISERVER_OPTS
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start kube-apiserver
systemctl enable kube-apiserver

### 3.3 部署kube-controller-manager
1> 创建配置文件
```html/xml
[root@km01 cfg]# cat /opt/kubernetes/cfg/kube-controller-manager.conf 
KUBE_CONTROLLER_MANAGER_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/kubernetes/logs \\
--leader-elect=true \\
--kubeconfig=/opt/kubernetes/cfg/kube-controller-manager.kubeconfig \\
--bind-address=127.0.0.1 \\
--allocate-node-cidrs=true \\
--cluster-cidr=10.244.0.0/16 \\
--service-cluster-ip-range=10.0.0.0/24 \\
--cluster-signing-cert-file=/opt/kubernetes/ssl/ca.pem \\
--cluster-signing-key-file=/opt/kubernetes/ssl/ca-key.pem  \\
--root-ca-file=/opt/kubernetes/ssl/ca.pem \\
--service-account-private-key-file=/opt/kubernetes/ssl/ca-key.pem \\
--experimental-cluster-signing-duration=87600h0m0s"

--kubeconfig:连接apiserver配置文件
--leader-elect:当该组件启动多个时,自动选举(HA)
--cluster-signing-cert-file/--cluster-signing-key-file:自动为kubelet颁发证书的CA,与apiserver保持一致

2> 生成kubeconfig文件
生成证书

cd /root/k8sssl
cat > kube-controller-manager-csr.json << EOF
{
  "CN": "system:kube-controller-manager",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "BeiJing", 
      "ST": "BeiJing",
      "O": "system:masters",
      "OU": "System"
    }
  ]
}
EOF

生成证书
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kube-controller-manager-csr.json | cfssljson -bare kube-controller-manager

生成kubeconfig文件

KUBE_CONFIG="/opt/kubernetes/cfg/kube-controller-manager.kubeconfig"
KUBE_APISERVER="https://192.168.1.31:6443"
kubectl config set-cluster kubernetes \\
  --certificate-authority=/opt/kubernetes/ssl/ca.pem \\
  --embed-certs=true \\
  --server=${KUBE_APISERVER} \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials kube-controller-manager \\
  --client-certificate=./kube-controller-manager.pem \\
  --client-key=./kube-controller-manager-key.pem \\
  --embed-certs=true \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \\
  --cluster=kubernetes \\
  --user=kube-controller-manager \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}

3> 设置开机启动

配置system管理文件
cat > /usr/lib/systemd/system/kube-controller-manager.service << EOF
[Unit]
Description=Kubernetes Controller Manager
Documentation=https://github.com/kubernetes/kubernetes

[Service]
EnvironmentFile=/opt/kubernetes/cfg/kube-controller-manager.conf
ExecStart=/opt/kubernetes/bin/kube-controller-manager \\$KUBE_CONTROLLER_MANAGER_OPTS
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
设置开机启动
systemctl daemon-reload
systemctl start kube-controller-manager
systemctl enable kube-controller-manager

3.4 kube-scheduler部署

1> kube-scheduler.conf 配置文件

cat > /opt/kubernetes/cfg/kube-scheduler.conf << EOF
KUBE_SCHEDULER_OPTS="--logtostderr=false \\\\
--v=2 \\\\
--log-dir=/opt/kubernetes/logs \\\\
--leader-elect \\\\
--kubeconfig=/opt/kubernetes/cfg/kube-scheduler.kubeconfig \\\\
--bind-address=127.0.0.1"
EOF

参数说明:
--kubeconfig:连接apiserver配置文件
--leader-elect:当该组件启动多个时,自动选举(HA)

2> 生成kubeconfig文件
生成kube-scheduler证书

cd /root/k8sssl
创建证书请求文件
cat > kube-scheduler-csr.json << EOF
{
  "CN": "system:kube-scheduler",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "BeiJing",
      "ST": "BeiJing",
      "O": "system:masters",
      "OU": "System"
    }
  ]
}
EOF
# 生成证书
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kube-scheduler-csr.json | cfssljson -bare kube-scheduler

3> 生成kubeconfig文件

KUBE_CONFIG="/opt/kubernetes/cfg/kube-scheduler.kubeconfig"
KUBE_APISERVER="https://192.168.1.31:6443"

kubectl config set-cluster kubernetes \\
  --certificate-authority=/opt/kubernetes/ssl/ca.pem \\
  --embed-certs=true \\
  --server=${KUBE_APISERVER} \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials kube-scheduler \\
  --client-certificate=./kube-scheduler.pem \\
  --client-key=./kube-scheduler-key.pem \\
  --embed-certs=true \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \\
  --cluster=kubernetes \\
  --user=kube-scheduler \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}

4> system管理、开机启动

cat > /usr/lib/systemd/system/kube-scheduler.service << EOF
[Unit]
Description=Kubernetes Scheduler
Documentation=https://github.com/kubernetes/kubernetes

[Service]
EnvironmentFile=/opt/kubernetes/cfg/kube-scheduler.conf
ExecStart=/opt/kubernetes/bin/kube-scheduler \\$KUBE_SCHEDULER_OPTS
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start kube-scheduler
systemctl enable kube-scheduler

5> 集群状态 (kubectl get cs)
kubelet连接集群证书

cat > admin-csr.json <<EOF
{
  "CN": "admin",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "BeiJing",
      "ST": "BeiJing",
      "O": "system:masters",
      "OU": "System"
    }
  ]
}
EOF
#生成证书
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes admin-csr.json | cfssljson -bare admin
#查看admin
[root@km01 k8sssl]# ls admin*
admin.csr  admin-csr.json  admin-key.pem  admin.pem

生成kubeconfig文件

mkdir /root/.kube
KUBE_CONFIG="/root/.kube/config"
KUBE_APISERVER="https://192.168.1.31:6443"

kubectl config set-cluster kubernetes \\
  --certificate-authority=/opt/kubernetes/ssl/ca.pem \\
  --embed-certs=true \\
  --server=${KUBE_APISERVER} \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials cluster-admin \\
  --client-certificate=./admin.pem \\
  --client-key=./admin-key.pem \\
  --embed-certs=true \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \\
  --cluster=kubernetes \\
  --user=cluster-admin \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}

查看集群状态

[root@km01 k8sssl]# kubectl get cs
NAME                 STATUS    MESSAGE             ERROR
scheduler            Healthy   ok                  
controller-manager   Healthy   ok                  
etcd-0               Healthy   {"health":"true"}   
etcd-1               Healthy   {"health":"true"}   
etcd-2               Healthy   {"health":"true"}   

6>授权kubelet-bootstrap用户允许证书请求

kubectl create clusterrolebinding kubelet-bootstrap \\
--clusterrole=system:node-bootstrapper \\
--user=kubelet-bootstrap

7> 部署CNI容器网络

[root@km01 ~]# cd ~
[root@km01 ~]#  wget https://github.com/containernetworking/plugins/releases/download/v0.8.6/cni-plugins-linux-amd64-v0.8.6.tgz
[root@km01 ~]# mkdir -pv /opt/cni/bin
[root@km01 ~]# tar xf cni-plugins-linux-amd64-v0.8.6.tgz -C /opt/cni/bin
[root@km01 ~]# ls /opt/cni/bin
bandwidth  bridge  dhcp  firewall  flannel  host-device  host-local  ipvlan  loopback  macvlan  portmap  ptp  sbr  static  tuning  vlan

三、部署node节点

master同时做为node节点

3.1 部署kubelet

1> 拷贝文件(master 或者 node 节点)

非master-node节点需要在node节点创建目录
mkdir -p /opt/kubernetes/{bin,cfg,ssl,logs}
从解压文件拷贝kubelet kube-proxy kubectl 
cp kubelet kube-proxy /opt/kubernetes/bin
cp kubectl /usr/local/bin

2> 创建kubelet.conf
拉取amd镜像

docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/pause-amd64:3.1

创建配置文件 kubelet.conf

cat > /opt/kubernetes/cfg/kubelet.conf << EOF
KUBELET_OPTS="--logtostderr=false \\\\
--v=2 \\\\
--log-dir=/opt/kubernetes/logs \\\\
--hostname-override=k8s-master1 \\\\
--network-plugin=cni \\\\
--kubeconfig=/opt/kubernetes/cfg/kubelet.kubeconfig \\\\
--bootstrap-kubeconfig=/opt/kubernetes/cfg/bootstrap.kubeconfig \\\\
--config=/opt/kubernetes/cfg/kubelet-config.yml \\\\
--cert-dir=/opt/kubernetes/ssl \\\\
--pod-infra-container-image=lizhenliang/pause-amd64:3.0"
EOF

参数说明:
--hostname-override:集群显示名称
--network-plugin:启用CNI
--kubeconfig:空路径,会自动生成,后面用于连接apiserver
--bootstrap-kubeconfig:首次启动向apiserver申请证书
--config:配置参数文件
--cert-dir:kubelet证书生成目录
--pod-infra-container-image:pause镜像700KB,解决Pod网络共享

3> 配置kubelet-config.yml 文件 | --config=/opt/kubernetes/cfg/kubelet-config.yml

cat > /opt/kubernetes/cfg/kubelet-config.yml << EOF
kind: KubeletConfiguration
apiVersion: kubelet.config.k8s.io/v1beta1
address: 0.0.0.0
port: 10250
readOnlyPort: 10255
cgroupDriver: cgroupfs
clusterDNS:
- 10.0.0.2
clusterDomain: cluster.local 
failSwapOn: false
authentication:
  anonymous:
    enabled: false
  webhook:
    cacheTTL: 2m0s
    enabled: true
  x509:
    clientCAFile: /opt/kubernetes/ssl/ca.pem 
authorization:
  mode: Webhook
  webhook:
    cacheAuthorizedTTL: 5m0s
    cacheUnauthorizedTTL: 30s
evictionHard:
  imagefs.available: 15%
  memory.available: 100Mi
  nodefs.available: 10%
  nodefs.inodesFree: 5%
maxOpenFiles: 1000000
maxPods: 110
EOF

4> 生成kubelet加入集群的kubeconfig文件

KUBE_CONFIG="/opt/kubernetes/cfg/bootstrap.kubeconfig"
KUBE_APISERVER="https://192.168.1.31:6443" // apiserver:6443
TOKEN=""  //与前token.csv一致
# 生成 kubelet bootstrap kubeconfig 配置文件
kubectl config set-cluster kubernetes \\
  --certificate-authority=/opt/kubernetes/ssl/ca.pem \\
  --embed-certs=true \\
  --server=${KUBE_APISERVER} \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials "kubelet-bootstrap" \\
  --token=${TOKEN} \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \\
  --cluster=kubernetes \\
  --user="kubelet-bootstrap" \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}

5> systemd管理、开机启动

cat > /usr/lib/systemd/system/kubelet.service << EOF
[Unit]
Description=Kubernetes Kubelet
After=docker.service

[Service]
EnvironmentFile=/opt/kubernetes/cfg/kubelet.conf
ExecStart=/opt/kubernetes/bin/kubelet \\$KUBELET_OPTS
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start kubelet
systemctl enable kubelet

6> 允许kubelet的证书申请准入集群

kubectl get csr
kubectl certificate approve `kubectl get csr | grep Pending| awk \'{print $1}\'`
kubectl get node |  可以看到km01 为not ready状态,是因为网络插件未安装

3.2 部署kube-proxy

1> 创建配置文件 kube-proxy.conf

[root@km01 cfg]# cat > /opt/kubernetes/cfg/kube-proxy.conf << EOF
KUBE_PROXY_OPTS="--logtostderr=false \\\\
--v=2 \\\\
--log-dir=/opt/kubernetes/logs \\\\
--config=/opt/kubernetes/cfg/kube-proxy-config.yml"
EOF

2> 创建kube-proxy-config.yml | kube-proxy.conf 中的--config=/opt/kubernetes/cfg/kube-proxy-config.yml

[root@km01 cfg]# cat > /opt/kubernetes/cfg/kube-proxy-config.yml  <<EOF
kind: KubeProxyConfiguration
apiVersion: kubeproxy.config.k8s.io/v1alpha1
bindAddress: 0.0.0.0
metricsBindAddress: 0.0.0.0:10249
clientConnection:
  kubeconfig: /opt/kubernetes/cfg/kube-proxy.kubeconfig
hostnameOverride: km01
clusterCIDR: 10.0.0.0/24
EOF

3> 生成kube-proxy.kubeconfig文件

cd /root/k8sssl
# 证书请求文件
cat > kube-proxy-csr.json << EOF
{
  "CN": "system:kube-proxy",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "BeiJing",
      "ST": "BeiJing",
      "O": "k8s",
      "OU": "System"
    }
  ]
}
EOF
#生成证书
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kube-proxy-csr.json | cfssljson -bare kube-proxy

生成kubeconfig文件

KUBE_CONFIG="/opt/kubernetes/cfg/kube-proxy.kubeconfig"
KUBE_APISERVER="https://192.168.1.31:6443"

kubectl config set-cluster kubernetes \\
  --certificate-authority=/opt/kubernetes/ssl/ca.pem \\
  --embed-certs=true \\
  --server=${KUBE_APISERVER} \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials kube-proxy \\
  --client-certificate=./kube-proxy.pem \\
  --client-key=./kube-proxy-key.pem \\
  --embed-certs=true \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \\
  --cluster=kubernetes \\
  --user=kube-proxy \\
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}

4> systemd、开机启动

cat > /usr/lib/systemd/system/kube-proxy.service << EOF
[Unit]
Description=Kubernetes Proxy
After=network.target

[Service]
EnvironmentFile=/opt/kubernetes/cfg/kube-proxy.conf
ExecStart=/opt/kubernetes/bin/kube-proxy \\$KUBE_PROXY_OPTS
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start kube-proxy
systemctl enable kube-proxy

3.3 flannel 安装

1> 创建目录

mkdir -p /etc/cni/ && mkdir -p /etc/kube-flannel

2> 下载kube-flannel 并安装

curl -o kube-flannel.yml  https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

#先拉取镜像执行文件
[root@km01 ~]# grep image kube-flannel.yml 
image: quay.io/coreos/flannel:v0.14.0
docker pull quay.io/coreos/flannel:v0.14.0
# apply flannel.yml
[root@km01 ~]# kubectl apply -f kube-flannel.yml 
podsecuritypolicy.policy/psp.flannel.unprivileged configured
clusterrole.rbac.authorization.k8s.io/flannel unchanged
clusterrolebinding.rbac.authorization.k8s.io/flannel unchanged
serviceaccount/flannel unchanged
configmap/kube-flannel-cfg unchanged
daemonset.apps/kube-flannel-ds unchanged
# kube-flannel 文件
---
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: psp.flannel.unprivileged
  annotations:
    seccomp.security.alpha.kubernetes.io/allowedProfileNames: docker/default
    seccomp.security.alpha.kubernetes.io/defaultProfileName: docker/default
    apparmor.security.beta.kubernetes.io/allowedProfileNames: runtime/default
    apparmor.security.beta.kubernetes.io/defaultProfileName: runtime/default
spec:
  privileged: false
  volumes:
  - configMap
  - secret
  - emptyDir
  - hostPath
  allowedHostPaths:
  - pathPrefix: "/etc/cni/net.d"
  - pathPrefix: "/etc/kube-flannel"
  - pathPrefix: "/run/flannel"
  readOnlyRootFilesystem: false
  # Users and groups
  runAsUser:
    rule: RunAsAny
  supplementalGroups:
    rule: RunAsAny
  fsGroup:
    rule: RunAsAny
  # Privilege Escalation
  allowPrivilegeEscalation: false
  defaultAllowPrivilegeEscalation: false
  # Capabilities
  allowedCapabilities: [\'NET_ADMIN\', \'NET_RAW\']
  defaultAddCapabilities: []
  requiredDropCapabilities: []
  # Host namespaces
  hostPID: false
  hostIPC: false
  hostNetwork: true
  hostPorts:
  - min: 0
    max: 65535
  # SELinux
  seLinux:
    # SELinux is unused in CaaSP
    rule: \'RunAsAny\'
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: flannel
rules:
- apiGroups: [\'extensions\']
  resources: [\'podsecuritypolicies\']
  verbs: [\'use\']
  resourceNames: [\'psp.flannel.unprivileged\']
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
- apiGroups:
  - ""
  resources:
  - nodes
  verbs:
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - nodes/status
  verbs:
  - patch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: flannel
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: flannel
subjects:
- kind: ServiceAccount
  name: flannel
  namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: flannel
  namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
  name: kube-flannel-cfg
  namespace: kube-system
  labels:
    tier: node
    app: flannel
data:
  cni-conf.json: |
    {
      "name": "cbr0",
      "cniVersion": "0.3.1",
      "plugins": [
        {
          "type": "flannel",
          "delegate": {
            "hairpinMode": true,
            "isDefaultGateway": true
          }
        },
        {
          "type": "portmap",
          "capabilities": {
            "portMappings": true
          }
        }
      ]
    }
  net-conf.json: |
    {
      "Network": "10.244.0.0/16",
      "Backend": {
        "Type": "vxlan"
      }
    }
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: kube-flannel-ds
  namespace: kube-system
  labels:
    tier: node
    app: flannel
spec:
  selector:
    matchLabels:
      app: flannel
  template:
    metadata:
      labels:
        tier: node
        app: flannel
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/os
                operator: In
                values:
                - linux
      hostNetwork: true
      priorityClassName: system-node-critical
      tolerations:
      - operator: Exists
        effect: NoSchedule
      serviceAccountName: flannel
      initContainers:
      - name: install-cni
        image: quay.io/coreos/flannel:v0.14.0
        command:
        - cp
        args:
        - -f
        - /etc/kube-flannel/cni-conf.json
        - /etc/cni/net.d/10-flannel.conflist
        volumeMounts:
        - name: cni
          mountPath: /etc/cni/net.d
        - name: flannel-cfg
          mountPath: /etc/kube-flannel/
      containers:
      - name: kube-flannel
        image: quay.io/coreos/flannel:v0.14.0
        command:
        - /opt/bin/flanneld
        args:
        - --ip-masq
        - --kube-subnet-mgr
        resources:
          requests:
            cpu: "100m"
            memory: "50Mi"
          limits:
            cpu: "100m"
            memory: "50Mi"
        securityContext:
          privileged: false
          capabilities:
            add: ["NET_ADMIN", "NET_RAW"]
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        volumeMounts:
        - name: run
          mountPath: /run/flannel
        - name: flannel-cfg
          mountPath: /etc/kube-flannel/
      volumes:
      - name: run
        hostPath:
          path: /run/flannel
      - name: cni
        hostPath:
          path: /etc/cni/net.d
      - name: flannel-cfg
        configMap:
          name: kube-flannel-cfg

3> 授权apiserver访问kubelet
在执行kubectl exec、run、logs 等命令时,apiserver会转发到kubelet。这里定义 RBAC规则,授权apiserver调用kubelet API"
apiserver-to-kubelet-rbac.yaml 文件

[root@km01 ~]# cat > apiserver-to-kubelet-rbac.yaml << EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: system:kube-apiserver-to-kubelet
rules:
  - apiGroups:
      - ""
    resources:
      - nodes/proxy
      - nodes/stats
      - nodes/log
      - nodes/spec
      - nodes/metrics
      - pods/log
    verbs:
      - "*"
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: system:kube-apiserver
  namespace: ""
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:kube-apiserver-to-kubelet
subjects:
  - apiGroup: rbac.authorization.k8s.io
    kind: User
    name: kubernetes
EOF

执行文件

[root@km01 ~]# kubectl apply -f apiserver-to-kubelet-rbac.yaml 
clusterrole.rbac.authorization.k8s.io/system:kube-apiserver-to-kubelet unchanged
clusterrolebinding.rbac.authorization.k8s.io/system:kube-apiserver unchanged

3.4 coredns 安装

1> 生成coredns.yaml

git clone https://github.com/coredns/deployment.git --depth=1
yum install epel-release -y && yum install jq
cd /root/deployment/kubernetes/
./deploy.sh -i 10.0.0.2 > coredns.yaml

coredns 文件内容:

[root@master kubernetes]# cat coredns.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: coredns
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: system:coredns
rules:
  - apiGroups:
    - ""
    resources:
    - endpoints
    - services
    - pods
    - namespaces
    verbs:
    - list
    - watch
  - apiGroups:
    - discovery.k8s.io
    resources:
    - endpointslices
    verbs:
    - list
    - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: system:coredns
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:coredns
subjects:
- kind: ServiceAccount
  name: coredns
  namespace: kube-system
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
data:
  Corefile: |
    .:53 {
        errors
        health {
          lameduck 5s
        }
        ready
        kubernetes cluster.local in-addr.arpa ip6.arpa {
          fallthrough in-addr.arpa ip6.arpa
        }
        prometheus :9153
        forward . /etc/resolv.conf {
          max_concurrent 1000
        }
        cache 30
        loop
        reload
        loadbalance
    }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: coredns
  namespace: kube-system
  labels:
    k8s-app: kube-dns
    kubernetes.io/name: "CoreDNS"
spec:
  # replicas: not specified here:
  # 1. Default is 1.
  # 2. Will be tuned in real time if DNS horizontal auto-scaling is turned on.
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
  selector:
    matchLabels:
      k8s-app: kube-dns
  template:
    metadata:
      labels:
        k8s-app: kube-dns
    spec:
      priorityClassName: system-cluster-critical
      serviceAccountName: coredns
      tolerations:
        - key: "CriticalAddonsOnly"
          operator: "Exists"
      nodeSelector:
        kubernetes.io/os: linux
      affinity:
         podAntiAffinity:
           preferredDuringSchedulingIgnoredDuringExecution:
           - weight: 100
             podAffinityTerm:
               labelSelector:
                 matchExpressions:
                   - key: k8s-app
                     operator: In
                     values: ["kube-dns"]
               topologyKey: kubernetes.io/hostname
      containers:
      - name: coredns
        image: coredns/coredns:1.8.4
        imagePullPolicy: IfNotPresent
        resources:
          limits:
            memory: 170Mi
          requests:
            cpu: 100m
            memory: 70Mi
        args: [ "-conf", "/etc/coredns/Corefile" ]
        volumeMounts:
        - name: config-volume
          mountPath: /etc/coredns
          readOnly: true
        ports:
        - containerPort: 53
          name: dns
          protocol: UDP
        - containerPort: 53
          name: dns-tcp
          protocol: TCP
        - containerPort: 9153
          name: metrics
          protocol: TCP
        securityContext:
          allowPrivilegeEscalation: false
          capabilities:
            add:
            - NET_BIND_SERVICE
            drop:
            - all
          readOnlyRootFilesystem: true
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 60
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 5
        readinessProbe:
          httpGet:
            path: /ready
            port: 8181
            scheme: HTTP
      dnsPolicy: Default
      volumes:
        - name: config-volume
          configMap:
            name: coredns
            items:
            - key: Corefile
              path: Corefile
---
apiVersion: v1
kind: Service
metadata:
  name: kube-dns
  namespace: kube-system
  annotations:
    prometheus.io/port: "9153"
    prometheus.io/scrape: "true"
  labels:
    k8s-app: kube-dns
    kubernetes.io/cluster-service: "true"
    kubernetes.io/name: "CoreDNS"
spec:
  selector:
    k8s-app: kube-dns
  clusterIP: 10.0.0.2
  ports:
  - name: dns
    port: 53
    protocol: UDP
  - name: dns-tcp
    port: 53
    protocol: TCP
  - name: metrics
    port: 9153
    protocol: TCP

2> 安装coredns

[root@km01 ~]# kubectl apply -f ./deployment/kubernetes/coredns.yaml
serviceaccount/coredns unchanged
clusterrole.rbac.authorization.k8s.io/system:coredns unchanged
clusterrolebinding.rbac.authorization.k8s.io/system:coredns unchanged
configmap/coredns unchanged
deployment.apps/coredns unchanged
service/kube-dns unchanged
# 查看coredns
[root@km01 ~]# kubectl get pods -o wide -n kube-system
NAME                       READY   STATUS    RESTARTS   AGE     IP             NODE     NOMINATED NODE   READINESS GATES
coredns-6d99d5879f-gqc28   1/1     Running   1          29h     10.244.1.3     km01     <none>           <none>

3> 测试coredns

[root@km01 ~]# cat coredns-test.yaml 
apiVersion: v1
kind: Pod
metadata: 
    name: busybox
    namespace: default
spec:
    containers:
      - image: busybox:1.28.4
        command:
          - sleep
          - "3600"
        imagePullPolicy: IfNotPresent
        name: busybox
    restartPolicy: Always

[root@km01 ~]# kubectl exec -it busybox sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl kubectl exec [POD] -- [COMMAND] instead.
/ # nslookup kubernetes
Server:    10.0.0.2
Address 1: 10.0.0.2 kube-dns.kube-system.svc.cluster.local

Name:      kubernetes
Address 1: 10.0.0.1 kubernetes.default.svc.cluster.local

四、新增node节点(非master)

4.1 安装docker

yum install docker-ce-18.09.9 -y
systemctl enable docker
systemctl start docker

4.2 拷贝文件到node节点

1> 拷贝node相关文件到新增加节点 192.168.1.82

在192.168.1.31(master-node)执行:
scp -r /opt/kubernetes root@node02:/opt/
scp -r /usr/lib/systemd/system/{kubelet,kube-proxy}.service root@node02:/usr/lib/system/system/

2> 删除kubelet证书和kubeconfig文件
以下文件是证书申请审批后自动生成的,每个Node不同,必须删除

在node02执行:
rm -f /opt/kubernetes/cfg/kubelet.kubeconfig 
rm -f /opt/kubernetes/ssl/kubelet*

3> 修改配置文件中的主机名

vim /opt/kubernetes/cfg/kubelet.conf
--hostname-override=node02

vim /opt/kubernetes/cfg/kube-proxy-config.yml
hostnameOverride: node02

4.3 启动kubelet kube-proxy

systemctl daemon-reload
systemctl start kubelet kube-proxy
systemctl enable kubelet kube-proxy
# status running 状态
systemctl status kubelet
systemctl status kube-proxy

4.4 master批准node的kubelet加入请求

# 查看
[root@km01 ~]# kubectl get csr
NAME                                                   AGE   SIGNERNAME                                    REQUESTOR           CONDITION
node-csr-XY1MTmwMz8rnYLFbib6OaRdI4lyK52cvffpu3BAO1vU   53s   kubernetes.io/kube-apiserver-client-kubelet   kubelet-bootstrap   Pending
# 批准
[root@km01 ~]# kubectl certificate approve node-csr-XY1MTmwMz8rnYLFbib6OaRdI4lyK52cvffpu3BAO1vU
certificatesigningrequest.certificates.k8s.io/node-csr-XY1MTmwMz8rnYLFbib6OaRdI4lyK52cvffpu3BAO1vU approved
[root@km01 ~]# kubectl get csr
NAME                                                   AGE     SIGNERNAME                                    REQUESTOR           CONDITION
node-csr-XY1MTmwMz8rnYLFbib6OaRdI4lyK52cvffpu3BAO1vU   4m57s   kubernetes.io/kube-apiserver-client-kubelet   kubelet-bootstrap   Approved,Issued

4.5 查看状态

1> 查看flannel部署状态

[root@km01 ~]# kubectl get pods -n kube-system -o wide
NAME                       READY   STATUS    RESTARTS   AGE   IP             NODE     NOMINATED NODE   READINESS GATES
kube-flannel-ds-j2nr7      1/1     Running   1          30h   192.168.1.31   km01     <none>           <none>
kube-flannel-ds-kg8n2      1/1     Running   1          30h   192.168.1.81   node01   <none>           <none>
kube-flannel-ds-nrl6q      1/1     Running   0          17m   192.168.1.82   node02   <none>           <none>
kube-flannel-ds-qbrxx      1/1     Running   1          29h   192.168.1.32   km02     <none>           <none>

2> 查看集群状态

[root@km01 ~]# kubectl get node -o wide
NAME     STATUS   ROLES    AGE     VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION                CONTAINER-RUNTIME
km01     Ready    <none>   31h     v1.18.6   192.168.1.31   <none>        CentOS Linux 7 (Core)   3.10.0-1160.36.2.el7.x86_64   docker://18.9.9
km02     Ready    <none>   28h     v1.18.6   192.168.1.32   <none>        CentOS Linux 7 (Core)   3.10.0-1160.36.2.el7.x86_64   docker://18.9.9
node01   Ready    <none>   30h     v1.18.6   192.168.1.81   <none>        CentOS Linux 7 (Core)   3.10.0-1160.36.2.el7.x86_64   docker://18.9.9
node02   Ready    <none>   3m45s   v1.18.6   192.168.1.82   <none>        CentOS Linux 7 (Core)   3.10.0-1160.36.2.el7.x86_64   docker://18.9.9

五、部署master02节点

1> docker安装(略)
2> 创建etcd ssl目录

mkdir -p /opt/etcd/ssl

3> 将master01文件拷贝至master02

scp -r /opt/kubernetes/ root@192.168.1.32:/opt
scp -r /opt/etcd/ssl root@192.168.1.32:/opt/etcd/
scp /usr/lib/systemd/system/kube* root@192.168.1.32:/usr/lib/systemd/system/
scp /usr/local/bin/kubectl root@192.168.1.32:/usr/local/bin/
scp -r /root/.kube root@192.168.1.32:~

4> 删除证书

rm -rf /opt/kubernetes/cfg/kubelet.kubeconfig
rm -rf /opt/kubernetes/ssl/kubelet*

5> 修改ip、主机名

vim /opt/kubernetes/cfg/kube-apiserver.conf
--bind-address=192.168.1.32 \\
--secure-port=6443 \\
--advertise-address=192.168.1.32 \\

vim /opt/kubernetes/cfg/kubelet.conf
--hostname-override=km02 \\

vim /opt/kubernetes/cfg/kube-proxy-config.yml
hostnameOverride: km02

6> 开机启动

systemctl daemon-reload
systemctl start kube-apiserver kube-controller-manager kube-scheduler kubelet kube-proxy
systemctl enable kube-apiserver kube-controller-manager kube-scheduler kubelet kube-proxy

7> 修改~/.kube/config连接ip

server: https://192.168.1.32:6443

8> 证书请求、批准

[root@km01 ~]# kubectl get csr
[root@km01 ~]# kubectl certificate approve `kubectl get csr | grep "Pending" | awk \'{print $1}\'`

9> 查看集群最终状态

[root@km02 ~]# kubectl get cs
NAME                 STATUS    MESSAGE             ERROR
scheduler            Healthy   ok                  
controller-manager   Healthy   ok                  
etcd-0               Healthy   {"health":"true"}   
etcd-1               Healthy   {"health":"true"}   
etcd-2               Healthy   {"health":"true"}   
[root@km02 ~]# kubectl get node -o wide
NAME     STATUS   ROLES    AGE   VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION                CONTAINER-RUNTIME
km01     Ready    <none>   45h   v1.18.6   192.168.1.31   <none>        CentOS Linux 7 (Core)   3.10.0-1160.36.2.el7.x86_64   docker://18.9.9
km02     Ready    <none>   43h   v1.18.6   192.168.1.32   <none>        CentOS Linux 7 (Core)   3.10.0-1160.36.2.el7.x86_64   docker://18.9.9
node01   Ready    <none>   45h   v1.18.6   192.168.1.81   <none>        CentOS Linux 7 (Core)   3.10.0-1160.36.2.el7.x86_64   docker://18.9.9
node02   Ready    <none>   14h   v1.18.6   192.168.1.82   <none>        CentOS Linux 7 (Core)   3.10.0-1160.36.2.el7.x86_64   docker://18.9.9

六、 node节点连接VIP

6.1 修改node节点(node01,node02)kubelet、kube-proxy的api-server_IP

vim /opt/kubernetes/cfg/bootstrap.kubeconfig
server: https://192.168.1.30

vim /opt/kubernetes/cfg/kubelet.kubeconfig
server: https://192.168.1.30:8443

vim /opt/kubernetes/cfgkube-proxy.kubeconfig
server: https://192.168.1.30:8443

6.2 批准node加入

[root@km01 ~]# kubectl get csr
NAME                                                   AGE   SIGNERNAME                                    REQUESTOR           CONDITION
node-csr-MnhFWNifNhUeRTRJ6m5sHUmvEOsuRGvlJWxAl_f_pdc   28m   kubernetes.io/kube-apiserver-client-kubelet   kubelet-bootstrap   Pending

[root@km01 ~]# kubectl certificate approved node-csr-MnhFWNifNhUeRTRJ6m5sHUmvEOsuRGvlJWxAl_f_pdc

七、ngx、haproxy 配置

6.1 拓扑

6.2 安装nginx

1> nginx 软件版本: nginx-1.20.1.tar.gz ,安装

tar xzvf nginx-1.20.1.tar.gz
yum install gcc* zlib zlib-devel openssl openssl-devel pcre-devel -y
cd nginx-1.20.1
./configure --with-http_v2_module --with-http_ssl_module --with-http_sub_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-http_realip_module --with-stream
make && make install 

2> nginx配置
两台ngx 配置相同内容如下,通过四层代理,监听本地8443端口,代理后端km01,km02的api-server:6443

stream {
     log_format main \'$remote_addr $upstream_addr - [$time_local] $status $upstream_bytes_sent\';
     access_log /var/log/nginx/k8s-access.log main;
     upstream k8s-apiserver {
     server 192.168.1.32:6443;
     server 192.168.1.31:6443;
     }
     server {
     listen 8443;
     proxy_pass k8s-apiserver;
     }
}

6.3 安装keepalived

1> 安装keepalived
yum install keepalived -y
2> keepalived配置
keepalived master配置 ,backup配置把优先级调低即可

global_defs {
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
   vrrp_skip_check_adv_addr

   vrrp_strict chk_ngx {
   script "/data/check_nginx.sh"
   interval 2 #2s 运行script行
   }
}

vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.1.30/24
    }
    track_script {
          chk_ngx
    }
}

3> check_nginx.sh 脚本

#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
# 判断nginx进程是否在线,如果不在尝试重启
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
fi
sleep 2 #等待2s再次检查,如果ngx未启动kill keepalived进程
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
chmod +x /etc/keepalived/check_nginx.sh

##八、 测试

[root@km01 ~]# netstat -anlput | grep 8443
tcp        0      0 0.0.0.0:8443            0.0.0.0:*               LISTEN      54187/nginx: master 
tcp        0      0 192.168.1.30:8443       192.168.1.81:46050      ESTABLISHED 54188/nginx: worker 
tcp        0      0 192.168.1.30:8443       192.168.1.81:46062      ESTABLISHED 54188/nginx: worker 

[root@node01 cfg]# curl -k https://192.168.1.30:8443/version
{
  "major": "1",
  "minor": "18",
  "gitVersion": "v1.18.6",
  "gitCommit": "dff82dc0de47299ab66c83c626e08b245ab19037",
  "gitTreeState": "clean",
  "buildDate": "2020-07-15T16:51:04Z",
  "goVersion": "go1.13.9",
  "compiler": "gc",
  "platform": "linux/amd64"

[root@km01 ~]# kubectl get pods -n kube-system -o wide
NAME                       READY   STATUS    RESTARTS   AGE    IP             NODE     NOMINATED NODE   READINESS GATES
coredns-6d99d5879f-gqc28   1/1     Running   5          3d6h   10.244.1.7     km01     <none>           <none>
kube-flannel-ds-j2nr7      1/1     Running   20         3d7h   192.168.1.31   km01     <none>           <none>
kube-flannel-ds-kg8n2      1/1     Running   5          3d7h   192.168.1.81   node01   <none>           <none>
kube-flannel-ds-nrl6q      1/1     Running   4          2d1h   192.168.1.82   node02   <none>           <none>
kube-flannel-ds-qbrxx      1/1     Running   7          3d6h   192.168.1.32   km02     <none>           <none>

后续继续更新完善!!!

以上是关于kubernetes 二进制多master部署 v-1.18.6的主要内容,如果未能解决你的问题,请参考以下文章

Kubernetes多Master节点集群二进制部署

Kubernetes节点服务搭建————二进制部署多节点服务搭建Dashboard UI部署

Kubernetes节点服务搭建————二进制部署多节点服务搭建Dashboard UI部署

Kubernetes节点服务搭建————二进制部署多节点服务搭建Dashboard UI部署

Kubernetes节点服务搭建————二进制部署多节点服务搭建Dashboard UI部署

Kubernetes多节点二进制部署