目前常见的 kubernetes 的安装方式主要有两种,二进制和 Kubeadm 初始化两种方式。但是 kubeadm 初始化会存在证书有效期只有 1 年的问题(除 kubelet-client、ca、proxy-ca 是 10 年外都是 1 年)。所以生产环境如果使用 kubeadm 初始化的话的建议修 kubernetes 源码重新编译。

  此文使用的 kubernetes 版本是 1.20.11。

修改源码

获取源码

  kubernetes 是一个开源的项目,源码托管在 github 上。对应的 仓库地址 是 https://github.com/kubernetes/kubernetes。在仓库的 Releases 中下载指定版本的源码。这里下载 1.20.11。

1
[root@master-01 ~]# wget https://github.com/kubernetes/kubernetes/archive/refs/tags/v1.20.11.tar.gz

Go 语言环境配置

  Go 语言环境的安装配置这里简单展示。详细内容请读者自行查阅资料。Go 版本选择的是 1.15.15。

1
2
3
4
5
6
[root@master-01 ~]# wget https://golang.org/dl/go1.15.15.linux-amd64.tar.gz
[root@master-01 ~]# tar -zxvf go1.15.15.linux-amd64.tar.gz -C /usr/local
[root@master-01 ~]# echo "export PATH=$PATH:/usr/local/go/bin" >> /etc/profile
[root@master-01 ~]# source /etc/profile
[root@master-01 ~]# go version
go version go1.15.15 linux/amd64

修改源码

  源码修改主要是修改 duration365d 参数的值。源码路径是 cmd/kubeadm/app/util/pkiutil/pki_helpers.go。原参数为* const duration365d = time. Hour * 24 * 365。讲改值修改为 const duration365d = time. Hour * 24 * 365 * 100*,修改为 100 年。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
[root@master-01 ~]# pwd
/root
[root@master-01 ~]# tar -zxvf v1.20.11.tar.gz
[root@master-01 ~]# mkdir src
[root@master-01 ~]# echo "export GOPATH=/root/" >> /etc/profile
[root@master-01 ~]# source /etc/profile
[root@master-01 ~]# mv kubernetes-1.20.11 src/
[root@master-01 ~]# cd src/kubernetes-1.20.11
[root@master-01 kubernetes-1.20.11]# ll
total 208
drwxrwxr-x 4 root root 4096 Sep 16 03:15 api
drwxrwxr-x 8 root root 4096 Sep 16 03:15 build
lrwxrwxrwx 1 root root 21 Sep 16 03:15 BUILD.bazel -> build/root/BUILD.root
drwxrwxr-x 2 root root 4096 Sep 16 03:15 CHANGELOG
lrwxrwxrwx 1 root root 19 Sep 16 03:15 CHANGELOG.md -> CHANGELOG/README.md
drwxrwxr-x 9 root root 4096 Sep 16 03:15 cluster
drwxrwxr-x 24 root root 4096 Sep 16 03:15 cmd
-rw-rw-r-- 1 root root 148 Sep 16 03:15 code-of-conduct.md
-rw-rw-r-- 1 root root 624 Sep 16 03:15 CONTRIBUTING.md
drwxrwxr-x 2 root root 4096 Sep 16 03:15 docs
-rw-rw-r-- 1 root root 35783 Sep 16 03:15 go.mod
-rw-rw-r-- 1 root root 59271 Sep 16 03:15 go.sum
drwxrwxr-x 12 root root 4096 Sep 16 03:15 hack
-rw-rw-r-- 1 root root 11358 Sep 16 03:15 LICENSE
drwxrwxr-x 3 root root 4096 Sep 16 03:15 LICENSES
drwxrwxr-x 2 root root 4096 Sep 16 03:15 logo
lrwxrwxrwx 1 root root 19 Sep 16 03:15 Makefile -> build/root/Makefile
lrwxrwxrwx 1 root root 35 Sep 16 03:15 Makefile.generated_files -> build/root/Makefile.generated_files
-rw-rw-r-- 1 root root 783 Sep 16 03:15 OWNERS
-rw-rw-r-- 1 root root 10395 Sep 16 03:15 OWNERS_ALIASES
drwxrwxr-x 33 root root 4096 Sep 16 03:15 pkg
drwxrwxr-x 3 root root 4096 Sep 16 03:15 plugin
-rw-rw-r-- 1 root root 3386 Sep 16 03:15 README.md
-rw-rw-r-- 1 root root 563 Sep 16 03:15 SECURITY_CONTACTS
drwxrwxr-x 4 root root 4096 Sep 16 03:15 staging
-rw-rw-r-- 1 root root 1110 Sep 16 03:15 SUPPORT.md
drwxrwxr-x 17 root root 4096 Sep 16 03:15 test
drwxrwxr-x 6 root root 4096 Sep 16 03:15 third_party
drwxrwxr-x 4 root root 4096 Sep 16 03:15 translations
drwxrwxr-x 15 root root 4096 Sep 16 03:15 vendor
lrwxrwxrwx 1 root root 20 Sep 16 03:15 WORKSPACE -> build/root/WORKSPACE
[root@master-01 ~]# vim staging/src/k8s.io/client-go/util/cert/cert.go
const duration365d = time.Hour * 24 * 365 * 10
# 将 38 行改成这样 ,也可以直接讲 66 行修改成这样 NotAfter: now.Add(duration365d * 100).UTC()
# 这里如果直接修改成这样会 const duration365d = time.Hour * 24 * 365 * 100 编译是会直接报错,会超出时间限制。
# 因为默认是 NotAfter: now.Add(duration365d * 10).UTC(),
# 存在证书最大时间设置 maxAge = 100 * time.Hour * 24 * 365 // 100 years fixtures
[root@master-01 ~]# vim cmd/kubeadm/app/constants/constants.go
CertificateValidity = time.Hour * 24 * 365 * 100 # 修改 49 行为这样
[root@master-01 ~]# make WHAT=cmd/kubeadm GOFLAGS=-v # 编译源码

  执行完上述操作的时候,会生成 kubeadm 可执行文件,路径位于。/_output/bin/。特别注意:这里的给出的修改行数是 1.20.11 的。其他版本源码未做研究。不确定行数是否和 1.20.11 一致。

关于修改证书有效期

  • 未修改证书且使用内置 ETCD 相关证书有效期
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@master-01 ~]# kubeadm alpha certs check-expiration
[check-expiration] Reading configuration from the cluster...
[check-expiration] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'

CERTIFICATE EXPIRES RESIDUAL TIME CERTIFICATE AUTHORITY EXTERNALLY MANAGED
admin.conf Oct 17, 2022 03:31 UTC 359d no
apiserver Oct 17, 2022 03:31 UTC 359d ca no
apiserver-etcd-client Oct 17, 2022 03:31 UTC 359d etcd-ca no
apiserver-kubelet-client Oct 17, 2022 03:31 UTC 359d ca no
controller-manager.conf Oct 17, 2022 03:31 UTC 359d no
etcd-healthcheck-client Oct 17, 2022 03:31 UTC 359d etcd-ca no
etcd-peer Oct 17, 2022 03:31 UTC 359d etcd-ca no
etcd-server Oct 17, 2022 03:31 UTC 359d etcd-ca no
front-proxy-client Oct 17, 2022 03:31 UTC 359d front-proxy-ca no
scheduler.conf Oct 17, 2022 03:31 UTC 359d no

CERTIFICATE AUTHORITY EXPIRES RESIDUAL TIME EXTERNALLY MANAGED
ca Oct 15, 2031 03:31 UTC 9y no
etcd-ca Oct 15, 2031 03:31 UTC 9y no
front-proxy-ca Oct 15, 2031 03:31 UTC 9y no
  • 未修改证书且使用外置 ETCD 集群相关证书有效期
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@master-01 ~]# kubeadm alpha certs check-expiration
Command "check-expiration" is deprecated, please use the same command under "kubeadm certs"
[check-expiration] Reading configuration from the cluster...
[check-expiration] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'

CERTIFICATE EXPIRES RESIDUAL TIME CERTIFICATE AUTHORITY EXTERNALLY MANAGED
admin.conf Oct 23, 2022 00:49 UTC 364d no
apiserver Oct 23, 2022 00:49 UTC 364d ca no
apiserver-kubelet-client Oct 23, 2022 00:49 UTC 364d ca no
controller-manager.conf Oct 23, 2022 00:49 UTC 364d no
front-proxy-client Oct 23, 2022 00:49 UTC 364d front-proxy-ca no
scheduler.conf Oct 23, 2022 00:49 UTC 364d no

CERTIFICATE AUTHORITY EXPIRES RESIDUAL TIME EXTERNALLY MANAGED
ca Oct 21, 2031 00:49 UTC 9y no
front-proxy-ca Oct 21, 2031 00:49 UTC 9y no

  这里由于使用了外置的 etcd 集群导致没有 etcd 相关证书信息。

  • 修改 cmd/kubeadm/app/constants/constants.go 中 CertificateValidity 参数和外置 ETCD 集群相关证书有效期
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@master-01 kubernetes-1.20.11]# kubeadm alpha certs check-expiration
Command "check-expiration" is deprecated, please use the same command under "kubeadm certs"
[check-expiration] Reading configuration from the cluster...
[check-expiration] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'

CERTIFICATE EXPIRES RESIDUAL TIME CERTIFICATE AUTHORITY EXTERNALLY MANAGED
admin.conf Sep 29, 2121 01:01 UTC 99y no
apiserver Sep 29, 2121 01:01 UTC 99y ca no
apiserver-kubelet-client Sep 29, 2121 01:01 UTC 99y ca no
controller-manager.conf Sep 29, 2121 01:01 UTC 99y no
front-proxy-client Sep 29, 2121 01:01 UTC 99y front-proxy-ca no
scheduler.conf Sep 29, 2121 01:01 UTC 99y no

CERTIFICATE AUTHORITY EXPIRES RESIDUAL TIME EXTERNALLY MANAGED
ca Oct 21, 2031 01:01 UTC 9y no
front-proxy-ca Oct 21, 2031 01:01 UTC 9y no
  • 修改 CertificateValidity 和 constants 参数和外置 ETCD 集群相关证书有效期
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@master-01 ~]# kubeadm alpha certs check-expiration
Command "check-expiration" is deprecated, please use the same command under "kubeadm certs"
[check-expiration] Reading configuration from the cluster...
[check-expiration] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'

CERTIFICATE EXPIRES RESIDUAL TIME CERTIFICATE AUTHORITY EXTERNALLY MANAGED
admin.conf Sep 29, 2121 01:11 UTC 99y no
apiserver Sep 29, 2121 01:11 UTC 99y ca no
apiserver-kubelet-client Sep 29, 2121 01:11 UTC 99y ca no
controller-manager.conf Sep 29, 2121 01:11 UTC 99y no
front-proxy-client Sep 29, 2121 01:11 UTC 99y front-proxy-ca no
scheduler.conf Sep 29, 2121 01:11 UTC 99y no

CERTIFICATE AUTHORITY EXPIRES RESIDUAL TIME EXTERNALLY MANAGED
ca Sep 29, 2121 01:11 UTC 99y no
front-proxy-ca Sep 29, 2121 01:11 UTC 99y no

  因此如果需要修改源码以改变证书相关有效期,所以可以从上述按需修改。

高可用组件初始化

高可用组件安装

  高可用组件选取 openresty 和 Keepalived。执行下面命令安装 openresty 和 keepalived,master-01/02/03 三个节点都要安装。

1
2
3
[root@master-01 ~]# wget https://openresty.org/package/centos/openresty.repo
[root@master-01 ~]# mv openresty.repo /etc/yum.repos.d/
[root@master-01 ~]# yum -y install keepalived openresty

Openresty 配置

  openresty 是一个基于 Nginx 和 Lua 的 Web 平台。其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用着 Nginx 同样的功能。三个节点 Openresty 的配置相同。如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[root@master-01 ~]# cat > /usr/local/openresty/nginx/conf/nginx.conf << EOF
user root;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;

events {
worker_connections 1024;
}

stream {
upstream api-server {
server 192.168.1.1:6443;
server 192.168.1.2:6443;
server 192.168.1.3:6443;
}
server {
listen 8443;
proxy_pass api-server;
}
}
EOF

Keepalived 配置

  三个节点的 Keepalived 的配置文件略有不同。但总体还是一样的。

  • master-01
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[root@master-01 ~]# cat > /etc/keepalived/keepalived.conf << EOF
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_apiserver {
script "/etc/keepalived/check_apiserver.sh" # api-server 的检测脚本
interval 5
weight -5
fall 2
rise 1
}
vrrp_instance VI_1 {
state MASTER # 主节点角色为 MASTER
interface ens192 # 修改为服务器的网卡接口名称
mcast_src_ip 192.168.1.1 # 修改为本机 IP,这里给出了 master-01 的 IP
virtual_router_id 51
priority 100 # 主节点优先级为 100 两个备用节点为 90
nopreempt
advert_int 2
authentication {
auth_type PASS
auth_pass K8SHA_KA_AUTH
}
virtual_ipaddress {
192.168.1.254 # VIP
}
track_script {
chk_apiserver
}
}
EOF
  • master-02
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
[root@master-02 ~]# cat > /etc/keepalived/keepalived.conf << EOF
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_apiserver {
script "/etc/keepalived/check_apiserver.sh" # api-server 的检测脚本
interval 5
weight -5
fall 2
rise 1
}
vrrp_instance VI_1 {
state BACKUP # 备节点角色为 BACKUP master-02/03 一样
interface ens192 # 修改为服务器的网卡接口名称
mcast_src_ip 192.168.1.2 # 修改为本机 IP,这里给出了 master-02 的 IP
virtual_router_id 51
priority 90 # 主节点优先级为 100 两个备用节点为 90
nopreempt
advert_int 2
authentication {
auth_type PASS
auth_pass K8SHA_KA_AUTH
}
virtual_ipaddress {
192.168.1.254 # VIP
}
track_script {
chk_apiserver
}
}

EOF
  • master-03
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[root@master-03 ~]# cat > /etc/keepalived/keepalived.conf << EOF
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_apiserver {
script "/etc/keepalived/check_apiserver.sh" # api-server 的检测脚本
interval 5
weight -5
fall 2
rise 1
}
vrrp_instance VI_1 {
state BACKUP # 备节点角色为 BACKUP master-02/03 一样
interface ens192 # 修改为服务器的网卡接口名称
mcast_src_ip 192.168.1.3 # 修改为本机 IP,这里给出了 master-03 的 IP
virtual_router_id 51
priority 90 # 主节点优先级为 100 两个备用节点为 90
nopreempt
advert_int 2
authentication {
auth_type PASS
auth_pass K8SHA_KA_AUTH
}
virtual_ipaddress {
192.168.1.254 # VIP
}
track_script {
chk_apiserver
}
}
EOF

Keepalived 检测脚本

  检测脚本用来检测 8443 端口的存活状态来改变 VIP 的状态的脚本。master-01/02/03 这三台服务器都是一样的,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[root@master-01 ~]# cat /etc/keepalived/check_apiserver.sh 
#!/bin/bash
err=0
for k in $(seq 1 3)
do
check_code=$(pgrep nginx)
if [[ $check_code == "" ]]; then
err=$(expr $err + 1)
sleep 1
continue
else
err=0
break
fi
done

if [[ $err != "0" ]]; then
echo "systemctl stop keepalived"
/usr/bin/systemctl stop keepalived
exit 1
else
exit 0
fi
[root@master-01 ~]# chmod 755 /etc/keepalived/check_apiserver.sh

启动高可用组件

  当 openresty 配置文件、keepalived 的配置文件和检测脚本都配好之后就该启动这两个服务了。

1
2
3
[root@master-01 ~]# systemctl daemon-reload
[root@master-01 ~]# systemctl enable --now openresty
[root@master-01 ~]# systemctl enable --now keepalived

Kubeadm 初始化

安装 K8S

  首先通过 YUM 安装对应的 kubelet、kubeadm、kubectl 等包。配置 Kubernetes 源主机 192.168.1.1-9 都要配置。

1
2
3
4
5
6
7
8
9
10
11
12
[root@master-01 ~]# cat > /etc/yum.repos.d/kubernetes.repo <<EOF
[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
[root@master-01 ~]# yum install -y kubelet-1.20.11 kubeadm-1.20.11 kubectl-1.20.11
[root@master-01 ~]# systemctl daemon-reload && systemctl enable kubelet # 配置 kubelet 开机启动

替换 Kubeadm

  先备份当前的 kubeadm 版本,然后将刚刚修改源码生成的 Kubeadm 移动到/usr/bin/下。master-01/02/03 都要进行这个操作。

1
2
[root@master-01 ~]# mv /usr/bin/kubeadm /usr/bin/kubeadm.bak
[root@master-01 ~]# mv /root/kubernetes/_output/bin/kubeadm /usr/bin/kubeadm

生成初始化配置文件

  kubeadm 可以直接执行生成默认的初始化 yaml 配置文件。这里通过初始化文件修改之后得到如下文件 kubeadm-init.yaml。请注意:etcd 的相关证书不能通过软连接访问。会报错。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
apiVersion: kubeadm.k8s.io/v1beta2
bootstrapTokens:
- groups:
- system:bootstrappers:kubeadm:default-node-token
token: 7t2weq.bjbawausm0jaxury
ttl: 24h0m0s
usages:
- signing
- authentication
kind: InitConfiguration
localAPIEndpoint:
advertiseAddress: 192.168.1.1
bindPort: 6443
nodeRegistration:
criSocket: /var/run/dockershim.sock
name: master-01
taints:
- effect: NoSchedule
key: node-role.kubernetes.io/master
---
apiServer:
certSANs:
- 192.168.1.254
timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta2
certificatesDir: /etc/kubernetes/pki
clusterName: kubernetes
controlPlaneEndpoint: 192.168.1.254:8443
controllerManager: {}
dns:
type: CoreDNS
etcd:
external:
endpoints:
- https://192.168.1.1:2379
- https://192.168.1.2:2379
- https://192.168.1.3:2379
caFile: /data/etcd/ssl/etcd-ca.pem
certFile: /data/etcd/ssl/etcd.pem
keyFile: /data/etcd/ssl/etcd-key.pem
imageRepository: registry.cn-hangzhou.aliyuncs.com/google_containers
kind: ClusterConfiguration
kubernetesVersion: v1.20.11
networking:
dnsDomain: cluster.local
podSubnet: 172.168.0.0/12
serviceSubnet: 10.96.0.0/12
scheduler: {}

集群初始化

  在配置好上述文件之后,我们就可以进行集群的初始化操作。

  • master-01
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
[root@master-01 ~]# kubeadm init --config kubeadm-init.yaml
[init] Using Kubernetes version: v1.20.11
[preflight] Running pre-flight checks
[WARNING SystemVerification]: this Docker version is not on the list of validated versions: 20.10.9. Latest validated version: 19.03
[WARNING Service-Kubelet]: kubelet service is not enabled, please run 'systemctl enable kubelet.service'
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "ca" certificate and key
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local master-01] and IPs [101.240.0.1 192.168.1.1 192.168.1.254]
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "front-proxy-ca" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] External etcd mode: Skipping etcd/ca certificate authority generation
[certs] External etcd mode: Skipping etcd/server certificate generation
[certs] External etcd mode: Skipping etcd/peer certificate generation
[certs] External etcd mode: Skipping etcd/healthcheck-client certificate generation
[certs] External etcd mode: Skipping apiserver-etcd-client certificate generation
[certs] Generating "sa" key and public key
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "admin.conf" kubeconfig file
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "kubelet.conf" kubeconfig file
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Starting the kubelet
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[apiclient] All control plane components are healthy after 13.008750 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.20" in namespace kube-system with the configuration for the kubelets in the cluster
[upload-certs] Skipping phase. Please see --upload-certs
[mark-control-plane] Marking the node master-01 as control-plane by adding the labels "node-role.kubernetes.io/master=''" and "node-role.kubernetes.io/control-plane='' (deprecated)"
[mark-control-plane] Marking the node master-01 as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: 9037x2.tcaqnpaqkra9vsbw
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to get nodes
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstrap-token] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstrap-token] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstrap-token] Creating the "cluster-info" ConfigMap in the "kube-public" namespace
[kubelet-finalize] Updating "/etc/kubernetes/kubelet.conf" to point to a rotatable kubelet client certificate and key
[addons] Applied essential addon: CoreDNS
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[addons] Applied essential addon: kube-proxy

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

Alternatively, if you are the root user, you can run:

export KUBECONFIG=/etc/kubernetes/admin.conf

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/

You can now join any number of control-plane nodes by copying certificate authorities
and service account keys on each node and then running the following as root:

kubeadm join 192.168.1.254:8443 --token 9037x2.tcaqnpaqkra9vsbw \
--discovery-token-ca-cert-hash sha256:4ec2e05c624bc200d3eef48540a4ca0db0cbda3dbb280559ddd9ec4f76475f6d \
--control-plane

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

kubeadm join 192.168.1.254:8443 --token 9037x2.tcaqnpaqkra9vsbw \
--discovery-token-ca-cert-hash sha256:4ec2e05c624bc200d3eef48540a4ca0db0cbda3dbb280559ddd9ec4f76475f6d

  在将 master-02、03 加入集群之前需要复制以下证书文件到 master-02/03 的/etc/kubernetes/pki 的目录下

/etc/kubernetes/pki/ca.crt

/etc/kubernetes/pki/ca.key

/etc/kubernetes/pki/sa.key

/etc/kubernetes/pki/sa.pub

/etc/kubernetes/pki/front-proxy-ca.crt

/etc/kubernetes/pki/front-proxy-ca.key

  • master-02
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
[root@master-02 ~]#   kubeadm join 192.168.1.254:8443 --token 9037x2.tcaqnpaqkra9vsbw     --discovery-token-ca-cert-hash sha256:4ec2e05c624bc200d3eef48540a4ca0db0cbda3dbb280559ddd9ec4f76475f6d     --control-plane 
[preflight] Running pre-flight checks
[WARNING SystemVerification]: this Docker version is not on the list of validated versions: 20.10.9. Latest validated version: 19.03
[WARNING Service-Kubelet]: kubelet service is not enabled, please run 'systemctl enable kubelet.service'
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
[preflight] Running pre-flight checks before initializing the new control plane instance
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local master-02] and IPs [101.240.0.1 192.168.1.2 192.168.1.254]
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] Valid certificates and keys now exist in "/etc/kubernetes/pki"
[certs] Using the existing "sa" key
[kubeconfig] Generating kubeconfig files
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "admin.conf" kubeconfig file
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[check-etcd] Skipping etcd check in external mode
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Starting the kubelet
[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...
[control-plane-join] using external etcd - no local stacked instance added
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[mark-control-plane] Marking the node master-02 as control-plane by adding the labels "node-role.kubernetes.io/master=''" and "node-role.kubernetes.io/control-plane='' (deprecated)"
[mark-control-plane] Marking the node master-02 as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]

This node has joined the cluster and a new control plane instance was created:

* Certificate signing request was sent to apiserver and approval was received.
* The Kubelet was informed of the new secure connection details.
* Control plane (master) label and taint were applied to the new node.
* The Kubernetes control plane instances scaled up.

To start administering your cluster from this node, 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

Run 'kubectl get nodes' to see this node join the cluster.
  • master-03
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
[root@master-03 ~]# kubeadm join 192.168.1.254:8443 --token 9037x2.tcaqnpaqkra9vsbw     --discovery-token-ca-cert-hash sha256:4ec2e05c624bc200d3eef48540a4ca0db0cbda3dbb280559ddd9ec4f76475f6d     --control-plane
[preflight] Running pre-flight checks
[WARNING SystemVerification]: this Docker version is not on the list of validated versions: 20.10.9. Latest validated version: 19.03
[WARNING Service-Kubelet]: kubelet service is not enabled, please run 'systemctl enable kubelet.service'
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
[preflight] Running pre-flight checks before initializing the new control plane instance
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local master-03] and IPs [101.240.0.1 192.168.13 192.168.1.254]
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] Valid certificates and keys now exist in "/etc/kubernetes/pki"
[certs] Using the existing "sa" key
[kubeconfig] Generating kubeconfig files
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "admin.conf" kubeconfig file
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[check-etcd] Skipping etcd check in external mode
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Starting the kubelet
[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...
[control-plane-join] using external etcd - no local stacked instance added
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[mark-control-plane] Marking the node master-03 as control-plane by adding the labels "node-role.kubernetes.io/master=''" and "node-role.kubernetes.io/control-plane='' (deprecated)"
[mark-control-plane] Marking the node master-03 as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]

This node has joined the cluster and a new control plane instance was created:

* Certificate signing request was sent to apiserver and approval was received.
* The Kubelet was informed of the new secure connection details.
* Control plane (master) label and taint were applied to the new node.
* The Kubernetes control plane instances scaled up.

To start administering your cluster from this node, 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

Run 'kubectl get nodes' to see this node join the cluster.

node 节点加入集群

  在需要加入集群的 worker 节点上执行一下操作。worker-01 至 worker-06 都需要执行一下操作。

1
2
[root@worker-01 ~]# kubeadm join 192.168.1.254:8443 --token 9037x2.tcaqnpaqkra9vsbw \
--discovery-token-ca-cert-hash sha256:4ec2e05c624bc200d3eef48540a4ca0db0cbda3dbb280559ddd9ec4f76475f6d

查看集群信息

  查看信息之前需要将 kubectl 的管理配置文件复制到家目录下的。kube 目录下。而初始化的时候已经给出命令。

1
2
3
4
5
6
7
8
[root@master-01 ~]# mkdir -p $HOME/.kube
[root@master-01 ~]# sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
[root@master-01 ~]# sudo chown $(id -u):$(id -g) $HOME/.kube/config
[root@master-01 ~]# kubectl get node
NAME STATUS ROLES AGE VERSION
master-01 NotReady control-plane,master 40m v1.20.11
master-02 NotReady control-plane,master 9m46s v1.20.11
master-03 NotReady control-plane,master 5m19s v1.20.11

  如果没有复制管理文件就出如下情况。

1
2
[root@master-02 ~]# 
The connection to the server localhost:8080 was refused - did you specify the right host or port?

  到这里集群的初始化基本已经完毕了。但执行”kubectl get pod -n kube-system“会发现如下出现 coredns 处于 Pending 状态。这里是由于没有网路插件导致的。安装好网络插件就会解决。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@master-01 ~]# kubectl get pod -n kube-system
NAME READY STATUS RESTARTS AGE
coredns-7f89b7bc75-676lc 0/1 Pending 0 54m
coredns-7f89b7bc75-k7q92 0/1 Pending 0 54m
kube-apiserver-master-01 1/1 Running 0 54m
kube-apiserver-master-02 1/1 Running 0 23m
kube-apiserver-master-03 1/1 Running 0 19m
kube-controller-manager-master-01 1/1 Running 0 54m
kube-controller-manager-master-02 1/1 Running 0 23m
kube-controller-manager-master-03 1/1 Running 0 19m
kube-proxy-cw2np 1/1 Running 0 23m
kube-proxy-kbqkw 1/1 Running 0 19m
kube-proxy-v5knr 1/1 Running 0 54m
kube-scheduler-master-01 1/1 Running 0 54m
kube-scheduler-master-02 1/1 Running 0 23m
kube-scheduler-master-03 1/1 Running 0 19m

插件安装

Calico

  在 K8S 上网络插件有很多,比如 Calico、flannel、Cilium、Weave 等。其中最常用的应该属 Calico 和 flannel 莫属。这里选择 Calico 作为网络插件。

  Calico 官网。我们需要下载 calico-etcd.yaml 文件。

1
2
3
4
5
6
7
8
9
[root@master-01 ~]# curl -O https://docs.projectcalico.org/manifests/calico-etcd.yaml
[root@master-01 ~]# # 使用 wget 会报错
[root@master-01 ~]# wget https://docs.projectcalico.org/manifests/calico-etcd.yaml
--2021-10-23 13:15:59-- https://docs.projectcalico.org/manifests/calico-etcd.yaml
Resolving docs.projectcalico.org (docs.projectcalico.org)... 178.128.126.116, 104.248.158.121, 2406:da18:880:3802:371c:4bf1:923b:fc30, ...
Connecting to docs.projectcalico.org (docs.projectcalico.org)|178.128.126.116|:443... connected.
ERROR: cannot verify docs.projectcalico.org's certificate, issued by ‘/C=US/O=Let's Encrypt/CN=R3’:
Issued certificate has expired.
To connect to docs.projectcalico.org insecurely, use `--no-check-certificate'.

  这里给出对应的一份完整的 calico-etcd.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
---
# Source: calico/templates/calico-etcd-secrets.yaml
# The following contains k8s Secrets for use with a TLS enabled etcd cluster.
# For information on populating Secrets, see http://kubernetes.io/docs/user-guide/secrets/
apiVersion: v1
kind: Secret
type: Opaque
metadata:
name: calico-etcd-secrets
namespace: kube-system
data:
# Populate the following with etcd TLS configuration if desired, but leave blank if
# not using TLS for etcd.
# The keys below should be uncommented and the values populated with the base64
# encoded contents of each file that would be associated with the TLS data.
# Example command for encoding a file contents: cat <file> | base64 -w 0
# etcd-key: null
# etcd-cert: null
# etcd-ca: null
---
# Source: calico/templates/calico-config.yaml
# This ConfigMap is used to configure a self-hosted Calico installation.
kind: ConfigMap
apiVersion: v1
metadata:
name: calico-config
namespace: kube-system
data:
# Configure this with the location of your etcd cluster.
etcd_endpoints: "http://<ETCD_IP>:<ETCD_PORT>"
# If you're using TLS enabled etcd uncomment the following.
# You must also populate the Secret below with these files.
etcd_ca: "" # "/calico-secrets/etcd-ca"
etcd_cert: "" # "/calico-secrets/etcd-cert"
etcd_key: "" # "/calico-secrets/etcd-key"
# Typha is disabled.
typha_service_name: "none"
# Configure the backend to use.
calico_backend: "bird"

# Configure the MTU to use for workload interfaces and tunnels.
# By default, MTU is auto-detected, and explicitly setting this field should not be required.
# You can override auto-detection by providing a non-zero value.
veth_mtu: "0"

# The CNI network configuration to install on each node. The special
# values in this config will be automatically populated.
cni_network_config: |-
{
"name": "k8s-pod-network",
"cniVersion": "0.3.1",
"plugins": [
{
"type": "calico",
"log_level": "info",
"log_file_path": "/var/log/calico/cni/cni.log",
"etcd_endpoints": "__ETCD_ENDPOINTS__",
"etcd_key_file": "__ETCD_KEY_FILE__",
"etcd_cert_file": "__ETCD_CERT_FILE__",
"etcd_ca_cert_file": "__ETCD_CA_CERT_FILE__",
"mtu": __CNI_MTU__,
"ipam": {
"type": "calico-ipam"
},
"policy": {
"type": "k8s"
},
"kubernetes": {
"kubeconfig": "__KUBECONFIG_FILEPATH__"
}
},
{
"type": "portmap",
"snat": true,
"capabilities": {"portMappings": true}
},
{
"type": "bandwidth",
"capabilities": {"bandwidth": true}
}
]
}

---
# Source: calico/templates/calico-kube-controllers-rbac.yaml

# Include a clusterrole for the kube-controllers component,
# and bind it to the calico-kube-controllers serviceaccount.
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: calico-kube-controllers
rules:
# Pods are monitored for changing labels.
# The node controller monitors Kubernetes nodes.
# Namespace and serviceaccount labels are used for policy.
- apiGroups: [""]
resources:
- pods
- nodes
- namespaces
- serviceaccounts
verbs:
- watch
- list
- get
# Watch for changes to Kubernetes NetworkPolicies.
- apiGroups: ["networking.k8s.io"]
resources:
- networkpolicies
verbs:
- watch
- list
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: calico-kube-controllers
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: calico-kube-controllers
subjects:
- kind: ServiceAccount
name: calico-kube-controllers
namespace: kube-system
---

---
# Source: calico/templates/calico-node-rbac.yaml
# Include a clusterrole for the calico-node DaemonSet,
# and bind it to the calico-node serviceaccount.
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: calico-node
rules:
# The CNI plugin needs to get pods, nodes, and namespaces.
- apiGroups: [""]
resources:
- pods
- nodes
- namespaces
verbs:
- get
# EndpointSlices are used for Service-based network policy rule
# enforcement.
- apiGroups: ["discovery.k8s.io"]
resources:
- endpointslices
verbs:
- watch
- list
- apiGroups: [""]
resources:
- endpoints
- services
verbs:
# Used to discover service IPs for advertisement.
- watch
- list
# Pod CIDR auto-detection on kubeadm needs access to config maps.
- apiGroups: [""]
resources:
- configmaps
verbs:
- get
- apiGroups: [""]
resources:
- nodes/status
verbs:
# Needed for clearing NodeNetworkUnavailable flag.
- patch

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: calico-node
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: calico-node
subjects:
- kind: ServiceAccount
name: calico-node
namespace: kube-system

---
# Source: calico/templates/calico-node.yaml
# This manifest installs the calico-node container, as well
# as the CNI plugins and network config on
# each master and worker node in a Kubernetes cluster.
kind: DaemonSet
apiVersion: apps/v1
metadata:
name: calico-node
namespace: kube-system
labels:
k8s-app: calico-node
spec:
selector:
matchLabels:
k8s-app: calico-node
updateStrategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
template:
metadata:
labels:
k8s-app: calico-node
spec:
nodeSelector:
kubernetes.io/os: linux
hostNetwork: true
tolerations:
# Make sure calico-node gets scheduled on all nodes.
- effect: NoSchedule
operator: Exists
# Mark the pod as a critical add-on for rescheduling.
- key: CriticalAddonsOnly
operator: Exists
- effect: NoExecute
operator: Exists
serviceAccountName: calico-node
# Minimize downtime during a rolling upgrade or deletion; tell Kubernetes to do a "force
# deletion": https://kubernetes.io/docs/concepts/workloads/pods/pod/#termination-of-pods.
terminationGracePeriodSeconds: 0
priorityClassName: system-node-critical
initContainers:
# This container installs the CNI binaries
# and CNI network config file on each node.
- name: install-cni
image: docker.io/calico/cni:v3.20.2
command: ["/opt/cni/bin/install"]
envFrom:
- configMapRef:
# Allow KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT to be overridden for eBPF mode.
name: kubernetes-services-endpoint
optional: true
env:
# Name of the CNI config file to create.
- name: CNI_CONF_NAME
value: "10-calico.conflist"
# The CNI network config to install on each node.
- name: CNI_NETWORK_CONFIG
valueFrom:
configMapKeyRef:
name: calico-config
key: cni_network_config
# The location of the etcd cluster.
- name: ETCD_ENDPOINTS
valueFrom:
configMapKeyRef:
name: calico-config
key: etcd_endpoints
# CNI MTU Config variable
- name: CNI_MTU
valueFrom:
configMapKeyRef:
name: calico-config
key: veth_mtu
# Prevents the container from sleeping forever.
- name: SLEEP
value: "false"
volumeMounts:
- mountPath: /host/opt/cni/bin
name: cni-bin-dir
- mountPath: /host/etc/cni/net.d
name: cni-net-dir
- mountPath: /calico-secrets
name: etcd-certs
securityContext:
privileged: true
# Adds a Flex Volume Driver that creates a per-pod Unix Domain Socket to allow Dikastes
# to communicate with Felix over the Policy Sync API.
- name: flexvol-driver
image: docker.io/calico/pod2daemon-flexvol:v3.20.2
volumeMounts:
- name: flexvol-driver-host
mountPath: /host/driver
securityContext:
privileged: true
containers:
# Runs calico-node container on each Kubernetes node. This
# container programs network policy and routes on each
# host.
- name: calico-node
image: docker.io/calico/node:v3.20.2
envFrom:
- configMapRef:
# Allow KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT to be overridden for eBPF mode.
name: kubernetes-services-endpoint
optional: true
env:
# The location of the etcd cluster.
- name: ETCD_ENDPOINTS
valueFrom:
configMapKeyRef:
name: calico-config
key: etcd_endpoints
# Location of the CA certificate for etcd.
- name: ETCD_CA_CERT_FILE
valueFrom:
configMapKeyRef:
name: calico-config
key: etcd_ca
# Location of the client key for etcd.
- name: ETCD_KEY_FILE
valueFrom:
configMapKeyRef:
name: calico-config
key: etcd_key
# Location of the client certificate for etcd.
- name: ETCD_CERT_FILE
valueFrom:
configMapKeyRef:
name: calico-config
key: etcd_cert
# Set noderef for node controller.
- name: CALICO_K8S_NODE_REF
valueFrom:
fieldRef:
fieldPath: spec.nodeName
# Choose the backend to use.
- name: CALICO_NETWORKING_BACKEND
valueFrom:
configMapKeyRef:
name: calico-config
key: calico_backend
# Cluster type to identify the deployment type
- name: CLUSTER_TYPE
value: "k8s,bgp"
# Auto-detect the BGP IP address.
- name: IP
value: "autodetect"
# Enable IPIP
- name: CALICO_IPV4POOL_IPIP
value: "Always"
# Enable or Disable VXLAN on the default IP pool.
- name: CALICO_IPV4POOL_VXLAN
value: "Never"
# Set MTU for tunnel device used if ipip is enabled
- name: FELIX_IPINIPMTU
valueFrom:
configMapKeyRef:
name: calico-config
key: veth_mtu
# Set MTU for the VXLAN tunnel device.
- name: FELIX_VXLANMTU
valueFrom:
configMapKeyRef:
name: calico-config
key: veth_mtu
# Set MTU for the Wireguard tunnel device.
- name: FELIX_WIREGUARDMTU
valueFrom:
configMapKeyRef:
name: calico-config
key: veth_mtu
# The default IPv4 pool to create on startup if none exists. Pod IPs will be
# chosen from this range. Changing this value after installation will have
# no effect. This should fall within `--cluster-cidr`.
# - name: CALICO_IPV4POOL_CIDR
# value: "192.168.0.0/16"
# Disable file logging so `kubectl logs` works.
- name: CALICO_DISABLE_FILE_LOGGING
value: "true"
# Set Felix endpoint to host default action to ACCEPT.
- name: FELIX_DEFAULTENDPOINTTOHOSTACTION
value: "ACCEPT"
# Disable IPv6 on Kubernetes.
- name: FELIX_IPV6SUPPORT
value: "false"
- name: FELIX_HEALTHENABLED
value: "true"
securityContext:
privileged: true
resources:
requests:
cpu: 250m
lifecycle:
preStop:
exec:
command:
- /bin/calico-node
- -shutdown
livenessProbe:
exec:
command:
- /bin/calico-node
- -felix-live
- -bird-live
periodSeconds: 10
initialDelaySeconds: 10
failureThreshold: 6
timeoutSeconds: 10
readinessProbe:
exec:
command:
- /bin/calico-node
- -felix-ready
- -bird-ready
periodSeconds: 10
timeoutSeconds: 10
volumeMounts:
# For maintaining CNI plugin API credentials.
- mountPath: /host/etc/cni/net.d
name: cni-net-dir
readOnly: false
- mountPath: /lib/modules
name: lib-modules
readOnly: true
- mountPath: /run/xtables.lock
name: xtables-lock
readOnly: false
- mountPath: /var/run/calico
name: var-run-calico
readOnly: false
- mountPath: /var/lib/calico
name: var-lib-calico
readOnly: false
- mountPath: /calico-secrets
name: etcd-certs
- name: policysync
mountPath: /var/run/nodeagent
# For eBPF mode, we need to be able to mount the BPF filesystem at /sys/fs/bpf so we mount in the
# parent directory.
- name: sysfs
mountPath: /sys/fs/
# Bidirectional means that, if we mount the BPF filesystem at /sys/fs/bpf it will propagate to the host.
# If the host is known to mount that filesystem already then Bidirectional can be omitted.
mountPropagation: Bidirectional
- name: cni-log-dir
mountPath: /var/log/calico/cni
readOnly: true
volumes:
# Used by calico-node.
- name: lib-modules
hostPath:
path: /lib/modules
- name: var-run-calico
hostPath:
path: /var/run/calico
- name: var-lib-calico
hostPath:
path: /var/lib/calico
- name: xtables-lock
hostPath:
path: /run/xtables.lock
type: FileOrCreate
- name: sysfs
hostPath:
path: /sys/fs/
type: DirectoryOrCreate
# Used to install CNI.
- name: cni-bin-dir
hostPath:
path: /opt/cni/bin
- name: cni-net-dir
hostPath:
path: /etc/cni/net.d
# Used to access CNI logs.
- name: cni-log-dir
hostPath:
path: /var/log/calico/cni
# Mount in the etcd TLS secrets with mode 400.
# See https://kubernetes.io/docs/concepts/configuration/secret/
- name: etcd-certs
secret:
secretName: calico-etcd-secrets
defaultMode: 0400
# Used to create per-pod Unix Domain Sockets
- name: policysync
hostPath:
type: DirectoryOrCreate
path: /var/run/nodeagent
# Used to install Flex Volume Driver
- name: flexvol-driver-host
hostPath:
type: DirectoryOrCreate
path: /usr/libexec/kubernetes/kubelet-plugins/volume/exec/nodeagent~uds
---

apiVersion: v1
kind: ServiceAccount
metadata:
name: calico-node
namespace: kube-system

---
# Source: calico/templates/calico-kube-controllers.yaml
# See https://github.com/projectcalico/kube-controllers
apiVersion: apps/v1
kind: Deployment
metadata:
name: calico-kube-controllers
namespace: kube-system
labels:
k8s-app: calico-kube-controllers
spec:
# The controllers can only have a single active instance.
replicas: 1
selector:
matchLabels:
k8s-app: calico-kube-controllers
strategy:
type: Recreate
template:
metadata:
name: calico-kube-controllers
namespace: kube-system
labels:
k8s-app: calico-kube-controllers
spec:
nodeSelector:
kubernetes.io/os: linux
tolerations:
# Mark the pod as a critical add-on for rescheduling.
- key: CriticalAddonsOnly
operator: Exists
- key: node-role.kubernetes.io/master
effect: NoSchedule
serviceAccountName: calico-kube-controllers
priorityClassName: system-cluster-critical
# The controllers must run in the host network namespace so that
# it isn't governed by policy that would prevent it from working.
hostNetwork: true
containers:
- name: calico-kube-controllers
image: docker.io/calico/kube-controllers:v3.20.2
env:
# The location of the etcd cluster.
- name: ETCD_ENDPOINTS
valueFrom:
configMapKeyRef:
name: calico-config
key: etcd_endpoints
# Location of the CA certificate for etcd.
- name: ETCD_CA_CERT_FILE
valueFrom:
configMapKeyRef:
name: calico-config
key: etcd_ca
# Location of the client key for etcd.
- name: ETCD_KEY_FILE
valueFrom:
configMapKeyRef:
name: calico-config
key: etcd_key
# Location of the client certificate for etcd.
- name: ETCD_CERT_FILE
valueFrom:
configMapKeyRef:
name: calico-config
key: etcd_cert
# Choose which controllers to run.
- name: ENABLED_CONTROLLERS
value: policy,namespace,serviceaccount,workloadendpoint,node
volumeMounts:
# Mount in the etcd TLS secrets.
- mountPath: /calico-secrets
name: etcd-certs
livenessProbe:
exec:
command:
- /usr/bin/check-status
- -l
periodSeconds: 10
initialDelaySeconds: 10
failureThreshold: 6
timeoutSeconds: 10
readinessProbe:
exec:
command:
- /usr/bin/check-status
- -r
periodSeconds: 10
volumes:
# Mount in the etcd TLS secrets with mode 400.
# See https://kubernetes.io/docs/concepts/configuration/secret/
- name: etcd-certs
secret:
secretName: calico-etcd-secrets
defaultMode: 0440

---

apiVersion: v1
kind: ServiceAccount
metadata:
name: calico-kube-controllers
namespace: kube-system

---

# This manifest creates a Pod Disruption Budget for Controller to allow K8s Cluster Autoscaler to evict

apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
name: calico-kube-controllers
namespace: kube-system
labels:
k8s-app: calico-kube-controllers
spec:
maxUnavailable: 1
selector:
matchLabels:
k8s-app: calico-kube-controllers

---
# Source: calico/templates/calico-typha.yaml

---
# Source: calico/templates/configure-canal.yaml

---
# Source: calico/templates/kdd-crds.yaml
  • 修改 etcd-enpoints 及对应的 screct。

  对应的修改路径如图所示
avatar

1
2
3
4
[root@master-01 ~]# sed -i 's#etcd_endpoints: "http://<ETCD_IP>:<ETCD_PORT>"#etcd_endpoints: "https://192.168.1.1:2379,https://192.168.1.2:2379,https://192.168.1.3:2379"#g' calico-etcd.yaml
[root@master-01 ~]# sed -i 's#etcd_ca: ""#etcd_ca: "/calico-secrets/etcd-ca"#g' calico-etcd.yaml
[root@master-01 ~]# sed -i 's#etcd_cert: ""#etcd_cert: "/calico-secrets/etcd-cert"#g' calico-etcd.yaml
[root@master-01 ~]# sed -i 's#etcd_key: "" #etcd_key: "/calico-secrets/etcd-key" #g' calico-etcd.yaml
  • 修改 Etcd 的访问证书

  修改 etcd 相关证书的访问认证。需要修改的位置如图所示。
avatar

1
2
3
4
5
6
[root@master-01 ~]# ETCD_CA=`cat /data/etcd/ssl/etcd-ca.pem | base64 | tr -d '\n'`
[root@master-01 ~]# ETCD_CERT=`cat /data/etcd/ssl/etcd.pem | base64 | tr -d '\n'`
[root@master-01 ~]# ETCD_KEY=`cat /data/etcd/ssl/etcd-key.pem | base64 | tr -d '\n'`
[root@master-01 ~]# sed -i "s@# etcd-key: null@etcd-key: ${ETCD_KEY}@g" calico-etcd.yaml
[root@master-01 ~]# sed -i "s@# etcd-cert: null@etcd-cert: ${ETCD_CERT}@g" calico-etcd.yaml
[root@master-01 ~]# sed -i "s@# etcd-ca: null@etcd-ca: ${ETCD_CA}@g" calico-etcd.yaml
  • 修改 Calico-Ipv4Pool-CIDR

  Calico-Ipv4Pool-CIDR 修改的位置如图所示。
avatar

1
2
[root@master-01 ~]# sed -i 's@# - name: CALICO_IPV4POOL_CIDR@- name: CALICO_IPV4POOL_CIDR@g' calico-etcd.yaml
[root@master-01 ~]# sed -i 's@# value: "192.168.0.0/16"@ value: '"172.168.0.0/12"'@g' calico-etcd.yaml
  • 安装
1
[root@master-01 ~]# kubectl apply -f calico-etcd.yaml

Metrics-Server

  Kubernetes 中系统资源的采集均使用 Metrics-server,可以通过 Metrics 采集节点和 Pod 的内存、磁盘、CPU 和网络的使用率。

  metrics-server 的源码托管在 github 上。仓库地址为 https://github.com/kubernetes-sigs/metrics-server。

  • metrics-server 的版本支持关系如下所示
Metrics Server Metrics API group/version Supported Kubernetes version
0.6.x metrics.k8s.io/v1beta1 *1.19+
0.5.x metrics.k8s.io/v1beta1 *1.8+
0.4.x metrics.k8s.io/v1beta1 *1.8+
0.3.x metrics.k8s.io/v1beta1 1.8-1.21
  • 下载 metrics-server 0.5.1
1
[root@master-01 ~]# wget https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.5.1/components.yaml
  • 修改 components.yaml 的镜像仓库

  components.yaml 中的镜像仓库是 k8s.gcr.io/metrics-server/metrics-server:v0.5.1。这个地址国内无法访问。所以需要修改地址为阿里云镜像 registry.aliyuncs.com/google_containers/metrics-server:v0.5.1。

  需要修改的内容如下图所示。
avatar

  • 部署 metrics-server
1
[root@master-01 ~]# kubectl apply -f components.yaml

  至此 Kubeadm 初始化高可用集群就 OK 了。