手动搭建高可用的 kubernetes 集群(v1.16.6)
1、组件版本和配置策略
1.1 主要组件版本
组件 | 版本 |
---|---|
kubernetes | 1.16.6 |
etcd | 3.4.3 |
containerd | 1.3.3 |
runc | 1.0.0-rc10 |
calico | 3.12.0 |
coredns | 1.6.6 |
dashboard | v2.0.0-rc4 |
k8s-prometheus-adapter | 0.5.0 |
prometheus-operator | 0.35.0 |
prometheus | 2.15.2 |
elasticsearch、kibana | 7.2.0 |
cni-plugins | 0.8.5 |
metrics-server | 0.3.6 |
1.2 主要配置策略
- kube-apiserver:
- 使用节点本地 nginx 4 层透明代理实现高可用;
- 关闭非安全端口 8080 和匿名访问;
- 在安全端口 6443 接收 https 请求;
- 严格的认证和授权策略 (x509、token、RBAC);
- 开启 bootstrap token 认证,支持 kubelet TLS bootstrapping;
- 使用 https 访问 kubelet、etcd,加密通信;
- kube-controller-manager:
- 3 节点高可用;
- 关闭非安全端口,在安全端口 10252 接收 https 请求;
- 使用 kubeconfig 访问 apiserver 的安全端口;
- 自动 approve kubelet 证书签名请求 (CSR),证书过期后自动轮转;
- 各 controller 使用自己的 ServiceAccount 访问 apiserver;
- kube-scheduler:
- 3 节点高可用;
- 使用 kubeconfig 访问 apiserver 的安全端口;
- kubelet:
- 使用 kubeadm 动态创建 bootstrap token,而不是在 apiserver 中静态配置;
- 使用 TLS bootstrap 机制自动生成 client 和 server 证书,过期后自动轮转;
- 在 KubeletConfiguration 类型的 JSON 文件配置主要参数;
- 关闭只读端口,在安全端口 10250 接收 https 请求,对请求进行认证和授权,拒绝匿名访问和非授权访问;
- 使用 kubeconfig 访问 apiserver 的安全端口;
- kube-proxy:
- 使用 kubeconfig 访问 apiserver 的安全端口;
- 在 KubeProxyConfiguration 类型的 JSON 文件配置主要参数;
- 使用 ipvs 代理模式;
- 集群插件:
- DNS:使用功能、性能更好的 coredns;
- Dashboard:支持登录认证;
- Metric:metrics-server,使用 https 访问 kubelet安全端口;
- Log:Elasticsearch、Fluend、Kibana;
- Registry 镜像库:docker-registry、harbor;
2、初始化系统和全局变量
2.1 集群规划
三台机器混合部署本文档的 etcd、master 集群和 woker 集群。
主机名称 | 物理IP | 说明 |
---|---|---|
k8s-01 | 192.168.200.11 | etcd 集群、Master 节点、Node 节点 |
k8s-02 | 192.168.200.12 | etcd 集群、Master 节点、Node 节点 |
k8s-03 | 192.168.200.13 | etcd 集群、Master 节点、Node 节点 |
2.2 初始化系统环境
2.2.1 关闭防火墙
关闭防火墙,清理防火墙规则,设置默认转发策略:
[root@k8s-01 ~]# systemctl stop firewalld
[root@k8s-01 ~]# systemctl disable firewalld
[root@k8s-01 ~]# iptables -F && iptables -X && iptables -F -t nat && iptables -X -t nat
[root@k8s-01 ~]# iptables -P FORWARD ACCEPT
2.2.2 关闭 swap 分区
关闭 swap 分区,否则kubelet 会启动失败(可以设置 kubelet 启动参数 --fail-swap-on 为 false 关闭 swap 检查):
[root@k8s-01 ~]# swapoff -a
[root@k8s-01 ~]# sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab
2.2.3 关闭 SELinux
关闭 SELinux,否则 kubelet 挂载目录时可能报错 Permission denied:
[root@k8s-01 ~]# setenforce 0
[root@k8s-01 ~]# sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
2.2.4 优化内核参数
[root@k8s-01 ~]# cat > /etc/sysctl.d/kubernetes.conf <<EOF
net.bridge.bridge-nf-call-iptables=1
net.bridge.bridge-nf-call-ip6tables=1
net.ipv4.ip_forward=1
net.ipv4.tcp_tw_recycle=0
net.ipv4.neigh.default.gc_thresh1=1024
net.ipv4.neigh.default.gc_thresh2=2048
net.ipv4.neigh.default.gc_thresh3=4096
vm.swappiness=0
vm.overcommit_memory=1
vm.panic_on_oom=0
fs.inotify.max_user_instances=8192
fs.inotify.max_user_watches=1048576
fs.file-max=52706963
fs.nr_open=52706963
net.ipv6.conf.all.disable_ipv6=1
net.netfilter.nf_conntrack_max=2310720
EOF
[root@k8s-01 ~]# modprobe br_netfilter
[root@k8s-01 ~]# sysctl -p /etc/sysctl.d/kubernetes.conf
- 关闭 tcp_tw_recycle,否则与 NAT 冲突,可能导致服务不通;
2.2.5 升级内核
CentOS 7.x 系统自带的 3.10.x 内核存在一些 Bugs,导致运行的 Docker、Kubernetes 不稳定,例如:
- 高版本的 docker(1.13 以后) 启用了 3.10 kernel 实验支持的 kernel memory account 功能(无法关闭),当节点压力大如频繁启动和停止容器时会导致 cgroup memory leak;
- 网络设备引用计数泄漏,会导致类似于报错:"kernel:unregister_netdevice: waiting for ens32 to become free. Usage count = 1";
解决方案如下:
- 升级内核到 4.4.X 以上;
- 或者,手动编译内核,disable CONFIG_MEMCG_KMEM 特性;
- 或者,安装修复了该问题的 Docker 18.09.1 及以上的版本。但由于 kubelet 也会设置 kmem(它 vendor 了 runc),所以需要重新编译 kubelet 并指定 GOFLAGS="-tags=nokmem";
这里采用升级内核的解决办法:
[root@k8s-01 ~]# rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-3.el7.elrepo.noarch.rpm
# 安装完成后检查 /boot/grub2/grub.cfg 中对应内核 menuentry 中是否包含 initrd16 配置,如果没有,再安装一次!
[root@k8s-01 ~]# yum --enablerepo=elrepo-kernel install -y kernel-lt
# 设置开机从新内核启动
[root@k8s-01 ~]# grub2-set-default 0
重启机器:
[root@k8s-01 ~]# sync
[root@k8s-01 ~]# reboot
参考
- 系统内核相关参数参考:https://docs.openshift.com/enterprise/3.2/admin_guide/overcommit.html
- 3.10.x 内核 kmem bugs 相关的讨论和解决办法:
- https://kubernetes/kubernetes#61937
- https://support.mesosphere.com/s/article/Critical-Issue-KMEM-MSPH-2018-0006
- https://pingcap.com/blog/try-to-fix-two-linux-kernel-bugs-while-testing-tidb-operator-in-k8s/
2.3 配置环境变量
2.3.1 配置映射
如果 DNS 不支持主机名称解析,还需要在每台机器的 /etc/hosts 文件
中添加主机名和 IP 的对应关系:
[root@k8s-01 ~]# cat >> /etc/hosts <<EOF
192.168.200.11 k8s-01
192.168.200.12 k8s-02
192.168.200.13 k8s-03
EOF
2.3.2 添加节点信任关系
本操作只需要在 k8s-01 节点上进行
,设置 root 账户可以无密码登录所有节点:
[root@k8s-01 ~]# ssh-keygen -t rsa
[root@k8s-01 ~]# ssh-copy-id root@k8s-01
[root@k8s-01 ~]# ssh-copy-id root@k8s-02
[root@k8s-01 ~]# ssh-copy-id root@k8s-03
2.3.3 创建相关目录
[root@k8s-01 ~]# mkdir -p /usr/k8s/bin /etc/{kubernetes,etcd}/ssl
2.3.4 分发集群配置参数脚本
后面的部署将会使用到的全局变量,定义如下(根据自己的机器、网络修改):
# 生成Token
[root@k8s-01 ~]# head -c 16 /dev/urandom | od -An -t x | tr -d ' '
1ff23e680b6cf205cd8a466a737f80b7
[root@k8s-01 ~]# cat >> environment.sh <<EOF
# TLS Bootstrapping 使用的Token
BOOTSTRAP_TOKEN="1ff23e680b6cf205cd8a466a737f80b7"
# 生成 EncryptionConfig 所需的加密 key
ENCRYPTION_KEY=$(head -c 32 /dev/urandom | base64)
# 当前部署的机器名称
NODE_NAME=k8s-01
# 集群各 IP 对应的主机名数组
NODE_NAMES=(k8s-01 k8s-02 k8s-03)
# 当前部署的机器IP
NODE_IP=192.168.200.11
# 集群各机器 IP 数组
export NODE_IPS=(192.168.200.11 192.168.200.12 192.168.200.13)
# etcd 集群服务地址列表
ETCD_ENDPOINTS="https://192.168.200.11:2379,https://192.168.200.12:2379,https://192.168.200.13:2379"
# etcd 集群间通信的IP和端口
export ETCD_NODES=k8s-01=https://192.168.200.11:2380,k8s-02=https://192.168.200.12:2380,k8s-03=https://192.168.200.13:2380
# kube-apiserver 的反向代理(kube-nginx)地址端口
KUBE_APISERVER="https://127.0.0.1:8443"
# etcd 数据目录
export ETCD_DATA_DIR="/data/k8s/etcd/data"
# etcd 工作目录
export ETCD_WAL_DIR="/data/k8s/etcd/wal"
# k8s 各组件数据目录
K8S_DIR="/data/k8s/k8s"
# containerd 数据目录
CONTAINERD_DIR="/data/k8s/containerd"
## 以下参数一般不需要修改
# 服务网段(Service CIDR),部署前路由不可达,部署后集群内部使用IP:Port可达
SERVICE_CIDR="10.254.0.0/16"
# Pod 网段(Cluster CIDR),部署前路由不可达,部署后路由可达(flanneld 保证)
CLUSTER_CIDR="172.30.0.0/16"
# 服务端口范围(NodePort Range)
NODE_PORT_RANGE="30000-32766"
# flanneld 网络配置前缀
FLANNEL_ETCD_PREFIX="/kubernetes/network"
# kubernetes 服务IP(预先分配,一般为SERVICE_CIDR中的第一个IP)
CLUSTER_KUBERNETES_SVC_IP="10.254.0.1"
# 集群 DNS 服务IP(从SERVICE_CIDR 中预先分配)
CLUSTER_DNS_SVC_IP="10.254.0.2"
# 集群 DNS 域名
CLUSTER_DNS_DOMAIN="cluster.local."
EOF
# 使全局变量生效
[root@k8s-01 ~]# source environment.sh
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p /usr/k8s/bin"
scp environment.sh root@${node_ip}:/usr/k8s/bin/
ssh root@${node_ip} "chmod +x /usr/k8s/bin/*"
done
# 更新 PATH 变量
[root@k8s-01 ~]# echo 'PATH=/usr/k8s/bin:$PATH' >> ~/.bashrc
[root@k8s-01 ~]# echo 'source /usr/k8s/bin/environment.sh' >> ~/.bashrc
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp ~/.bashrc root@${node_ip}:~/
done
3、创建 CA 根证书和秘钥
为确保安全,kubernetes
系统各组件需要使用 x509
证书对通信进行加密和认证。
CA (Certificate Authority) 是自签名的根证书,用来签名后续创建的其它证书。
CA 证书是集群所有节点共享的,只需要创建一次,后续用它签名其它所有证书。
本文档使用 CloudFlare
的 PKI 工具集 cfssl 创建所有证书。
3.1 安装 cfssl 工具集
[root@k8s-01 ~]# wget https://github.com/cloudflare/cfssl/releases/download/v1.4.1/cfssl_1.4.1_linux_amd64
[root@k8s-01 ~]# mv cfssl_1.4.1_linux_amd64 /usr/k8s/bin/cfssl
[root@k8s-01 ~]# wget https://github.com/cloudflare/cfssl/releases/download/v1.4.1/cfssljson_1.4.1_linux_amd64
[root@k8s-01 ~]# mv cfssljson_1.4.1_linux_amd64 /usr/k8s/bin/cfssljson
[root@k8s-01 ~]# wget https://github.com/cloudflare/cfssl/releases/download/v1.4.1/cfssl-certinfo_1.4.1_linux_amd64
[root@k8s-01 ~]# mv cfssl-certinfo_1.4.1_linux_amd64 /usr/k8s/bin/cfssl-certinfo
[root@k8s-01 ~]# chmod +x /usr/k8s/bin/cfssl*
3.2 创建配置文件
CA 配置文件用于配置根证书的使用场景 (profile) 和具体参数 (usage,过期时间、服务端认证、客户端认证、加密等):
[root@k8s-01 ~]# cat > ca-config.json <<EOF
{
"signing": {
"default": {
"expiry": "87600h"
},
"profiles": {
"kubernetes": {
"expiry": "876000h",
"usages": [
"signing",
"key encipherment",
"server auth",
"client auth"
]
}
}
}
}
EOF
signing
:表示该证书可用于签名其它证书(生成的ca.pem
证书中CA=TRUE
);server auth
:表示 client 可以用该该证书对 server 提供的证书进行验证;client auth
:表示 server 可以用该该证书对 client 提供的证书进行验证;"expiry"
: "876000h":证书有效期设置为 100 年;
3.3 创建证书签名请求文件
[root@k8s-01 ~]# cat > ca-csr.json <<EOF
{
"CN": "kubernetes",
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"ST": "BeiJing",
"L": "BeiJing",
"O": "k8s",
"OU": "System"
}
],
"ca": {
"expiry": "876000h"
}
}
EOF
CN:Common Name
:kube-apiserver 从证书中提取该字段作为请求的用户名 (User Name),浏览器使用该字段验证网站是否合法;O:Organization
:kube-apiserver 从证书中提取该字段作为请求用户所属的组 (Group);- kube-apiserver 将提取的
User、Group
作为RBAC
授权的用户标识;
注意:
- 不同证书 csr 文件的 CN、C、ST、L、O、OU 组合必须不同,否则可能出现
PEER'S CERTIFICATE HAS AN INVALID SIGNATURE
错误;- 后续创建证书的 csr 文件时,CN 都不相同(C、ST、L、O、OU 相同),以达到区分的目的;
3.4 生成 CA 证书和私钥
[root@k8s-01 ~]# cfssl gencert -initca ca-csr.json | cfssljson -bare ca
3.5 分发证书文件
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp ca*.pem ca-config.json root@${node_ip}:/etc/kubernetes/ssl
done
4、安装和配置 kubectl
本文档介绍安装和配置 kubernetes 命令行管理工具 kubectl 的步骤。
注意:
- 本文档只需要部署一次,生成的 kubeconfig 文件是通用的,可以拷贝到需要执行 kubectl 命令的机器的
~/.kube/config
位置;
4.1 下载和分发 kubectl 二进制文件
[root@k8s-01 ~]# wget https://dl.k8s.io/v1.16.6/kubernetes-client-linux-amd64.tar.gz
[root@k8s-01 ~]# tar xf kubernetes-client-linux-amd64.tar.gz
分发到所有使用 kubectl 工具的节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp kubernetes/client/bin/kubectl root@${node_ip}:/usr/k8s/bin/
ssh root@${node_ip} "chmod +x /usr/k8s/bin/*"
done
4.2 创建 admin 证书和私钥
kubectl 使用 https 协议与 kube-apiserver 进行安全通信,kube-apiserver 对 kubectl 请求包含的证书进行认证和授权。
kubectl 后续用于集群管理,所以这里创建具有最高权限的 admin 证书。
4.2.1 创建证书签名请求:
[root@k8s-01 ~]# cat > admin-csr.json <<EOF
{
"CN": "admin",
"hosts": [],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"ST": "BeiJing",
"L": "BeiJing",
"O": "system:masters",
"OU": "System"
}
]
}
EOF
O: system:masters
:kube-apiserver 收到使用该证书的客户端请求后,为请求添加组(Group)认证标识system:masters
;- 预定义的 ClusterRoleBinding
cluster-admin
将Group system:masters
与 Rolecluster-admin
绑定,该 Role 授予操作集群所需的最高权限;- 该证书只会被 kubectl 当做 client 证书使用,所以
hosts
字段为空;
4.2.2 生成证书和私钥:
[root@k8s-01 ~]# cfssl gencert -ca=/etc/kubernetes/ssl/ca.pem \
-ca-key=/etc/kubernetes/ssl/ca-key.pem \
-config=/etc/kubernetes/ssl/ca-config.json \
-profile=kubernetes admin-csr.json | cfssljson -bare admin
- 忽略警告消息
[WARNING] This certificate lacks a "hosts" field.
;
4.2.3 分发证书文件
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp admin*.pem root@${node_ip}:/etc/kubernetes/ssl
done
4.2.4 创建 kubeconfig 文件
kubectl 使用 kubeconfig 文件访问 apiserver,该文件包含 kube-apiserver 的地址和认证信息(CA 证书和客户端证书):
# 设置集群参数
[root@k8s-01 ~]# kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/ssl/ca.pem \
--embed-certs=true \
--server=https://${NODE_IPS[0]}:6443 \
--kubeconfig=kubectl.kubeconfig
# 设置客户端认证参数
[root@k8s-01 ~]# kubectl config set-credentials admin \
--client-certificate=/etc/kubernetes/ssl/admin.pem \
--client-key=/etc/kubernetes/ssl/admin-key.pem \
--embed-certs=true \
--kubeconfig=kubectl.kubeconfig
# 设置上下文参数
[root@k8s-01 ~]# kubectl config set-context kubernetes \
--cluster=kubernetes \
--user=admin \
--kubeconfig=kubectl.kubeconfig
# 设置默认上下文
[root@k8s-01 ~]# kubectl config use-context kubernetes --kubeconfig=kubectl.kubeconfig
--certificate-authority
:验证 kube-apiserver 证书的根证书;--client-certificate
、--client-key
:刚生成的admin
证书和私钥,与 kube-apiserver https 通信时使用;--embed-certs=true
:将 ca.pem 和 admin.pem 证书内容嵌入到生成的 kubectl.kubeconfig 文件中(否则,写入的是证书文件路径,后续拷贝 kubeconfig 到其它机器时,还需要单独拷贝证书文件,不方便。);--server
:指定 kube-apiserver 的地址,这里指向第一个节点上的服务;
4.3 分发 kubeconfig 文件
分发到所有使用 kubectl 命令的节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p ~/.kube"
scp kubectl.kubeconfig root@${node_ip}:~/.kube/config
done
5、部署 etcd 集群
etcd 是基于 Raft 的分布式 KV 存储系统,由 CoreOS 开发,常用于服务发现、共享配置以及并发控制(如 leader 选举、分布式锁等)。
kubernetes 使用 etcd 集群持久化存储所有 API 对象、运行数据。
本文档介绍部署一个三节点高可用 etcd 集群的步骤:
- 下载和分发 etcd 二进制文件;
- 创建 etcd 集群各节点的 x509 证书,用于加密客户端(如 etcdctl) 与 etcd 集群、etcd 集群之间的通信;
- 创建 etcd 的 systemd unit 文件,配置服务参数;
- 检查集群工作状态;
etcd 集群节点名称和 IP 如下:
- k8s-01:192.168.200.11
- k8s-02:192.168.200.12
- k8s-03:192.168.200.13
注意:
- lanneld 与本文档安装的 etcd v3.4.x 不兼容,如果要安装 flanneld(本文档使用 calio),则需要将 etcd 降级到 v3.3.x 版本;
5.1 下载和分发 etcd 二进制文件
到 etcd 的 release 页面 下载最新版本的发布包:
[root@k8s-01 ~]# wget https://github.com/coreos/etcd/releases/download/v3.4.3/etcd-v3.4.3-linux-amd64.tar.gz
[root@k8s-01 ~]# tar xf etcd-v3.4.3-linux-amd64.tar.gz
分发二进制文件到集群所有节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp etcd-v3.4.3-linux-amd64/etcd* root@${node_ip}:/usr/k8s/bin
ssh root@${node_ip} "chmod +x /usr/k8s/bin/*"
done
5.2 创建 etcd 证书和私钥
5.2.1 创建证书签名请求:
[root@k8s-01 ~]# cat > etcd-csr.json <<EOF
{
"CN": "etcd",
"hosts": [
"127.0.0.1",
"192.168.200.11",
"192.168.200.12",
"192.168.200.13"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"ST": "BeiJing",
"L": "BeiJing",
"O": "k8s",
"OU": "System"
}
]
}
EOF
hosts
:指定授权使用该证书的 etcd 节点 IP 列表,需要将 etcd 集群所有节点 IP 都列在其中;
5.2.2 生成证书和私钥:
[root@k8s-01 ~]# cfssl gencert -ca=/etc/kubernetes/ssl/ca.pem \
-ca-key=/etc/kubernetes/ssl/ca-key.pem \
-config=/etc/kubernetes/ssl/ca-config.json \
-profile=kubernetes etcd-csr.json | cfssljson -bare etcd
5.2.3 分发生成的证书和私钥到各 etcd 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp etcd*.pem root@${node_ip}:/etc/etcd/ssl/
done
5.3 创建 etcd 的 systemd unit 模板文件
[root@k8s-01 ~]# cat > etcd.service.template <<EOF
[Unit]
Description=Etcd Server
After=network.target
After=network-online.target
Wants=network-online.target
Documentation=https://github.com/coreos
[Service]
Type=notify
WorkingDirectory=${ETCD_DATA_DIR}
ExecStart=/usr/k8s/bin/etcd \\
--data-dir=${ETCD_DATA_DIR} \\
--wal-dir=${ETCD_WAL_DIR} \\
--name=##NODE_NAME## \\
--cert-file=/etc/etcd/ssl/etcd.pem \\
--key-file=/etc/etcd/ssl/etcd-key.pem \\
--trusted-ca-file=/etc/kubernetes/ssl/ca.pem \\
--peer-cert-file=/etc/etcd/ssl/etcd.pem \\
--peer-key-file=/etc/etcd/ssl/etcd-key.pem \\
--peer-trusted-ca-file=/etc/kubernetes/ssl/ca.pem \\
--peer-client-cert-auth \\
--client-cert-auth \\
--listen-peer-urls=https://##NODE_IP##:2380 \\
--initial-advertise-peer-urls=https://##NODE_IP##:2380 \\
--listen-client-urls=https://##NODE_IP##:2379,http://127.0.0.1:2379 \\
--advertise-client-urls=https://##NODE_IP##:2379 \\
--initial-cluster-token=etcd-cluster-0 \\
--initial-cluster=${ETCD_NODES} \\
--initial-cluster-state=new \\
--auto-compaction-mode=periodic \\
--auto-compaction-retention=1 \\
--max-request-bytes=33554432 \\
--quota-backend-bytes=6442450944 \\
--heartbeat-interval=250 \\
--election-timeout=2000
Restart=on-failure
RestartSec=5
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
WorkingDirectory
、--data-dir
:指定工作目录和数据目录为${ETCD_DATA_DIR}
,需在启动服务前创建这个目录;--wal-dir
:指定 wal 目录,为了提高性能,一般使用 SSD 或者和--data-dir
不同的磁盘;--name
:指定节点名称,当--initial-cluster-state
值为new
时,--name
的参数值必须位于--initial-cluster
列表中;--cert-file
、--key-file
:etcd server 与 client 通信时使用的证书和私钥;--trusted-ca-file
:签名 client 证书的 CA 证书,用于验证 client 证书;--peer-cert-file
、--peer-key-file
:etcd 与 peer 通信使用的证书和私钥;--peer-trusted-ca-file
:签名 peer 证书的 CA 证书,用于验证 peer 证书;
5.4 为各节点创建和分发 etcd systemd unit 文件
替换模板文件中的变量,为各节点创建 systemd unit 文件:
[root@k8s-01 ~]# for (( i=0; i < 3; i++ ))
do
sed -e "s/##NODE_NAME##/${NODE_NAMES[i]}/" -e "s/##NODE_IP##/${NODE_IPS[i]}/" etcd.service.template > etcd-${NODE_IPS[i]}.service
done
- NODE_NAMES 和 NODE_IPS 为相同长度的 bash 数组,分别为节点名称和对应的 IP;
分发生成的 systemd unit 文件:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp etcd-${node_ip}.service root@${node_ip}:/etc/systemd/system/etcd.service
done
5.5 启动 etcd 服务
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p ${ETCD_DATA_DIR} ${ETCD_WAL_DIR}"
ssh root@${node_ip} "systemctl daemon-reload && systemctl enable etcd && systemctl restart etcd " &
done
- 必须先创建 etcd 数据目录和工作目录;
- etcd 进程首次启动时会等待其它节点的 etcd 加入集群,命令
systemctl start etcd
会卡住一段时间,为正常现象;
5.6 检查启动结果
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "systemctl status etcd|grep Active"
done
确保状态为 active (running)
,否则查看日志,确认原因:
journalctl -u etcd
5.7 验证服务状态
部署完 etcd 集群后,在任一 etcd 节点上执行如下命令:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
/usr/k8s/bin/etcdctl \
--endpoints=https://${node_ip}:2379 \
--cacert=/etc/kubernetes/ssl/ca.pem \
--cert=/etc/etcd/ssl/etcd.pem \
--key=/etc/etcd/ssl/etcd-key.pem endpoint health
done
预期输出:
>>> 192.168.200.11
https://192.168.200.11:2379 is healthy: successfully committed proposal: took = 5.703401ms
>>> 192.168.200.12
https://192.168.200.12:2379 is healthy: successfully committed proposal: took = 6.626391ms
>>> 192.168.200.13
https://192.168.200.13:2379 is healthy: successfully committed proposal: took = 6.210975ms
输出均为 healthy 时表示集群服务正常。
查看当前的 leader
[root@k8s-01 ~]# /usr/k8s/bin/etcdctl \
-w table --cacert=/etc/kubernetes/ssl/ca.pem \
--cert=/etc/etcd/ssl/etcd.pem \
--key=/etc/etcd/ssl/etcd-key.pem \
--endpoints=${ETCD_ENDPOINTS} endpoint status
输出:
+-----------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
| ENDPOINT | ID | VERSION | DB SIZE | IS LEADER | IS LEARNER | RAFT TERM | RAFT INDEX | RAFT APPLIED INDEX | ERRORS |
+-----------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
| https://192.168.200.11:2379 | 95c5677668e390bf | 3.4.3 | 20 kB | true | false | 2 | 8 | 8 | |
| https://192.168.200.12:2379 | 9a5f17f14609fb12 | 3.4.3 | 25 kB | false | false | 2 | 8 | 8 | |
| https://192.168.200.13:2379 | 4250492deb6b449b | 3.4.3 | 20 kB | false | false | 2 | 8 | 8 | |
+-----------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
- 可见,当前的 leader 为 192.168.200.11
6、部署 master 节点
kubernetes master 节点运行如下组件:
- kube-apiserver
- kube-scheduler
- kube-controller-manager
kube-apiserver、kube-scheduler 和 kube-controller-manager 均以多实例模式运行:
- kube-scheduler 和 kube-controller-manager 会自动选举产生一个 leader 实例,其它实例处于阻塞模式,当 leader 挂了后,重新选举产生新的 leader,从而保证服务可用性;
- kube-apiserver 是无状态的,可以通过 kube-nginx 进行代理访问,从而保证服务可用性;
6.1 下载最新版本二进制文件
从 CHANGELOG 页面 下载二进制 tar 文件并解压:
[root@k8s-01 ~]# wget https://dl.k8s.io/v1.16.6/kubernetes-server-linux-amd64.tar.gz
[root@k8s-01 ~]# tar xf kubernetes-server-linux-amd64.tar.gz
[root@k8s-01 ~]# cd kubernetes
[root@k8s-01 kubernetes]# tar xf kubernetes-src.tar.gz
将二进制文件拷贝到所有 master 节点:
[root@k8s-01 kubernetes]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp server/bin/{apiextensions-apiserver,kube-apiserver,kube-controller-manager,kube-proxy,kube-scheduler,kubeadm,kubectl,kubelet,mounter} root@${node_ip}:/usr/k8s/bin/
ssh root@${node_ip} "chmod +x /usr/k8s/bin/*"
done
6.2 部署 kube-apiserver 集群
本文档讲解部署一个三实例 kube-apiserver 集群的步骤.
6.2.1 创建 kubernetes-master 证书和私钥
创建证书签名请求:
[root@k8s-01 ~]# cat > kubernetes-csr.json <<EOF
{
"CN": "kubernetes-master",
"hosts": [
"127.0.0.1",
"192.168.200.11",
"192.168.200.12",
"192.168.200.13",
"${CLUSTER_KUBERNETES_SVC_IP}",
"kubernetes",
"kubernetes.default",
"kubernetes.default.svc",
"kubernetes.default.svc.cluster",
"kubernetes.default.svc.cluster.local.",
"kubernetes.default.svc.${CLUSTER_DNS_DOMAIN}."
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"ST": "BeiJing",
"L": "BeiJing",
"O": "k8s",
"OU": "System"
}
]
}
EOF
- hosts 字段指定授权使用该证书的 IP 和域名列表,这里列出了 master 节点 IP、kubernetes 服务的 IP 和域名;
生成证书和私钥:
[root@k8s-01 ~]# cfssl gencert -ca=/etc/kubernetes/ssl/ca.pem \
-ca-key=/etc/kubernetes/ssl/ca-key.pem \
-config=/etc/kubernetes/ssl/ca-config.json \
-profile=kubernetes kubernetes-csr.json | cfssljson -bare kubernetes
将生成的证书和私钥文件拷贝到所有 master 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp kubernetes*.pem root@${node_ip}:/etc/kubernetes/ssl/
done
6.2.2 创建加密配置文件
[root@k8s-01 ~]# cat > encryption-config.yaml <<EOF
kind: EncryptionConfig
apiVersion: v1
resources:
- resources:
- secrets
providers:
- aescbc:
keys:
- name: key1
secret: ${ENCRYPTION_KEY}
- identity: {}
EOF
将加密配置文件拷贝到 master 节点的 /etc/kubernetes/work
目录下:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p /etc/kubernetes/work"
scp encryption-config.yaml root@${node_ip}:/etc/kubernetes/work/
done
6.2.3 创建审计策略文件
[root@k8s-01 ~]# cat > audit-policy.yaml <<EOF
apiVersion: audit.k8s.io/v1beta1
kind: Policy
rules:
# The following requests were manually identified as high-volume and low-risk, so drop them.
- level: None
resources:
- group: ""
resources:
- endpoints
- services
- services/status
users:
- 'system:kube-proxy'
verbs:
- watch
- level: None
resources:
- group: ""
resources:
- nodes
- nodes/status
userGroups:
- 'system:nodes'
verbs:
- get
- level: None
namespaces:
- kube-system
resources:
- group: ""
resources:
- endpoints
users:
- 'system:kube-controller-manager'
- 'system:kube-scheduler'
- 'system:serviceaccount:kube-system:endpoint-controller'
verbs:
- get
- update
- level: None
resources:
- group: ""
resources:
- namespaces
- namespaces/status
- namespaces/finalize
users:
- 'system:apiserver'
verbs:
- get
# Don't log HPA fetching metrics.
- level: None
resources:
- group: metrics.k8s.io
users:
- 'system:kube-controller-manager'
verbs:
- get
- list
# Don't log these read-only URLs.
- level: None
nonResourceURLs:
- '/healthz*'
- /version
- '/swagger*'
# Don't log events requests.
- level: None
resources:
- group: ""
resources:
- events
# node and pod status calls from nodes are high-volume and can be large, don't log responses
# for expected updates from nodes
- level: Request
omitStages:
- RequestReceived
resources:
- group: ""
resources:
- nodes/status
- pods/status
users:
- kubelet
- 'system:node-problem-detector'
- 'system:serviceaccount:kube-system:node-problem-detector'
verbs:
- update
- patch
- level: Request
omitStages:
- RequestReceived
resources:
- group: ""
resources:
- nodes/status
- pods/status
userGroups:
- 'system:nodes'
verbs:
- update
- patch
# deletecollection calls can be large, don't log responses for expected namespace deletions
- level: Request
omitStages:
- RequestReceived
users:
- 'system:serviceaccount:kube-system:namespace-controller'
verbs:
- deletecollection
# Secrets, ConfigMaps, and TokenReviews can contain sensitive & binary data,
# so only log at the Metadata level.
- level: Metadata
omitStages:
- RequestReceived
resources:
- group: ""
resources:
- secrets
- configmaps
- group: authentication.k8s.io
resources:
- tokenreviews
# Get repsonses can be large; skip them.
- level: Request
omitStages:
- RequestReceived
resources:
- group: ""
- group: admissionregistration.k8s.io
- group: apiextensions.k8s.io
- group: apiregistration.k8s.io
- group: apps
- group: authentication.k8s.io
- group: authorization.k8s.io
- group: autoscaling
- group: batch
- group: certificates.k8s.io
- group: extensions
- group: metrics.k8s.io
- group: networking.k8s.io
- group: policy
- group: rbac.authorization.k8s.io
- group: scheduling.k8s.io
- group: settings.k8s.io
- group: storage.k8s.io
verbs:
- get
- list
- watch
# Default level for known APIs
- level: RequestResponse
omitStages:
- RequestReceived
resources:
- group: ""
- group: admissionregistration.k8s.io
- group: apiextensions.k8s.io
- group: apiregistration.k8s.io
- group: apps
- group: authentication.k8s.io
- group: authorization.k8s.io
- group: autoscaling
- group: batch
- group: certificates.k8s.io
- group: extensions
- group: metrics.k8s.io
- group: networking.k8s.io
- group: policy
- group: rbac.authorization.k8s.io
- group: scheduling.k8s.io
- group: settings.k8s.io
- group: storage.k8s.io
# Default level for all other requests.
- level: Metadata
omitStages:
- RequestReceived
EOF
分发审计策略文件:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp audit-policy.yaml root@${node_ip}:/etc/kubernetes/work/audit-policy.yaml
done
6.2.4 创建后续访问 metrics-server 或 kube-prometheus 使用的证书
创建证书签名请求:
[root@k8s-01 ~]# cat > proxy-client-csr.json <<EOF
{
"CN": "aggregator",
"hosts": [],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"ST": "BeiJing",
"L": "BeiJing",
"O": "k8s",
"OU": "System"
}
]
}
EOF
- CN 名称需要位于 kube-apiserver 的
--requestheader-allowed-names
参数中,否则后续访问 metrics 时会提示权限不足。
生成证书和私钥:
[root@k8s-01 ~]# cfssl gencert -ca=/etc/kubernetes/ssl/ca.pem \
-ca-key=/etc/kubernetes/ssl/ca-key.pem \
-config=/etc/kubernetes/ssl/ca-config.json \
-profile=kubernetes proxy-client-csr.json | cfssljson -bare proxy-client
将生成的证书和私钥文件拷贝到所有 master 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp proxy-client*.pem root@${node_ip}:/etc/kubernetes/ssl/
done
6.2.5 创建 kube-apiserver systemd unit 模板文件
[root@k8s-01 ~]# cat > kube-apiserver.service.template <<EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
After=network.target
[Service]
WorkingDirectory=${K8S_DIR}/kube-apiserver
ExecStart=/usr/k8s/bin/kube-apiserver \\
--advertise-address=##NODE_IP## \\
--default-not-ready-toleration-seconds=360 \\
--default-unreachable-toleration-seconds=360 \\
--feature-gates=DynamicAuditing=true \\
--max-mutating-requests-inflight=2000 \\
--max-requests-inflight=4000 \\
--default-watch-cache-size=200 \\
--delete-collection-workers=2 \\
--encryption-provider-config=/etc/kubernetes/work/encryption-config.yaml \\
--etcd-cafile=/etc/kubernetes/ssl/ca.pem \\
--etcd-certfile=/etc/kubernetes/ssl/kubernetes.pem \\
--etcd-keyfile=/etc/kubernetes/ssl/kubernetes-key.pem \\
--etcd-servers=${ETCD_ENDPOINTS} \\
--bind-address=##NODE_IP## \\
--secure-port=6443 \\
--tls-cert-file=/etc/kubernetes/ssl/kubernetes.pem \\
--tls-private-key-file=/etc/kubernetes/ssl/kubernetes-key.pem \\
--insecure-port=0 \\
--audit-dynamic-configuration \\
--audit-log-maxage=15 \\
--audit-log-maxbackup=3 \\
--audit-log-maxsize=100 \\
--audit-log-truncate-enabled \\
--audit-log-path=${K8S_DIR}/kube-apiserver/audit.log \\
--audit-policy-file=/etc/kubernetes/work/audit-policy.yaml \\
--profiling \\
--anonymous-auth=false \\
--client-ca-file=/etc/kubernetes/ssl/ca.pem \\
--enable-bootstrap-token-auth \\
--requestheader-allowed-names="aggregator" \\
--requestheader-client-ca-file=/etc/kubernetes/ssl/ca.pem \\
--requestheader-extra-headers-prefix="X-Remote-Extra-" \\
--requestheader-group-headers=X-Remote-Group \\
--requestheader-username-headers=X-Remote-User \\
--service-account-key-file=/etc/kubernetes/ssl/ca.pem \\
--authorization-mode=Node,RBAC \\
--runtime-config=api/all=true \\
--enable-admission-plugins=NodeRestriction \\
--allow-privileged=true \\
--apiserver-count=3 \\
--event-ttl=168h \\
--kubelet-certificate-authority=/etc/kubernetes/ssl/ca.pem \\
--kubelet-client-certificate=/etc/kubernetes/ssl/kubernetes.pem \\
--kubelet-client-key=/etc/kubernetes/ssl/kubernetes-key.pem \\
--kubelet-https=true \\
--kubelet-timeout=10s \\
--proxy-client-cert-file=/etc/kubernetes/ssl/proxy-client.pem \\
--proxy-client-key-file=/etc/kubernetes/ssl/proxy-client-key.pem \\
--service-cluster-ip-range=${SERVICE_CIDR} \\
--service-node-port-range=${NODE_PORT_RANGE} \\
--logtostderr=true \\
--v=2
Restart=on-failure
RestartSec=10
Type=notify
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
--advertise-address
:apiserver 对外通告的 IP(kubernetes 服务后端节点 IP);--default-*-toleration-seconds
:设置节点异常相关的阈值;--max-*-requests-inflight
:请求相关的最大阈值;--etcd-*
:访问 etcd 的证书和 etcd 服务器地址;--bind-address
: https 监听的 IP,不能为127.0.0.1
,否则外界不能访问它的安全端口 6443;--secret-port
:https 监听端口;--insecure-port=0
:关闭监听 http 非安全端口(8080);--tls-*-file
:指定 apiserver 使用的证书、私钥和 CA 文件;--audit-*
:配置审计策略和审计日志文件相关的参数;--client-ca-file
:验证 client (kue-controller-manager、kube-scheduler、kubelet、kube-proxy 等)请求所带的证书;--enable-bootstrap-token-auth
:启用 kubelet bootstrap 的 token 认证;--requestheader-*
:kube-apiserver 的 aggregator layer 相关的配置参数,proxy-client & HPA 需要使用;--requestheader-client-ca-file
:用于签名--proxy-client-cert-file
和--proxy-client-key-file
指定的证书;在启用了 metric aggregator 时使用;--requestheader-allowed-names
:不能为空,值为逗号分割的--proxy-client-cert-file
证书的 CN 名称,这里设置为 "aggregator";--service-account-key-file
:签名 ServiceAccount Token 的公钥文件,kube-controller-manager 的--service-account-private-key-file
指定私钥文件,两者配对使用;--runtime-config=api/all=true
: 启用所有版本的 APIs,如 autoscaling/v2alpha1;--authorization-mode=Node,RBAC
、--anonymous-auth=false
: 开启 Node 和 RBAC 授权模式,拒绝未授权的请求;--enable-admission-plugins
:启用一些默认关闭的 plugins;--allow-privileged
:运行执行 privileged 权限的容器;--apiserver-count=3
:指定 apiserver 实例的数量;--event-ttl
:指定 events 的保存时间;--kubelet-*
:如果指定,则使用 https 访问 kubelet APIs;需要为证书对应的用户(上面 kubernetes*.pem 证书的用户为 kubernetes) 用户定义 RBAC 规则,否则访问 kubelet API 时提示未授权;--proxy-client-*
:apiserver 访问 metrics-server 使用的证书;--service-cluster-ip-range
: 指定 Service Cluster IP 地址段;--service-node-port-range
: 指定 NodePort 的端口范围;
如果 kube-apiserver 机器没有运行 kube-proxy,则还需要添加 --enable-aggregator-routing=true
参数;
关于 --requestheader-XXX
相关参数,参考:
- https://github.com/kubernetes-incubator/apiserver-builder/blob/master/docs/concepts/auth.md
- https://docs.bitnami.com/kubernetes/how-to/configure-autoscaling-custom-metrics/
注意:
--requestheader-client-ca-file
指定的 CA 证书,必须具有client auth and server auth
;- 如果
--requestheader-allowed-names
不为空,且--proxy-client-cert-file
证书的 CN 名称不在 allowed-names 中,则后续查看 node 或 pods 的 metrics 失败,提示:
[root@k8s-01 ~]# kubectl get nodes
The connection to the server 192.168.200.11:6443 was refused - did you specify the right host or port?
6.2.6 为各节点创建和分发 kube-apiserver systemd unit 文件
替换模板文件中的变量,为各节点生成 systemd unit 文件:
[root@k8s-01 ~]# for (( i=0; i < 3; i++ ))
do
sed -e "s/##NODE_NAME##/${NODE_NAMES[i]}/" -e "s/##NODE_IP##/${NODE_IPS[i]}/" kube-apiserver.service.template > kube-apiserver-${NODE_IPS[i]}.service
done
- NODE_NAMES 和 NODE_IPS 为相同长度的 bash 数组,分别为节点名称和对应的 IP;
分发生成的 systemd unit 文件:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp kube-apiserver-${node_ip}.service root@${node_ip}:/etc/systemd/system/kube-apiserver.service
done
6.2.7 启动 kube-apiserver 服务
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p ${K8S_DIR}/kube-apiserver"
ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-apiserver && systemctl restart kube-apiserver"
done
检查 kube-apiserver 运行状态
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "systemctl status kube-apiserver |grep 'Active:'"
done
确保状态为 active (running)
,否则查看日志,确认原因:
journalctl -u kube-apiserver
检查集群状态
[root@k8s-01 ~]# kubectl cluster-info
Kubernetes master is running at https://192.168.200.11:6443
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
[root@k8s-01 ~]# kubectl get all --all-namespaces
NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
default service/kubernetes ClusterIP 10.254.0.1 <none> 443/TCP 39s
[root@k8s-01 ~]# kubectl get componentstatuses
NAME AGE
scheduler <unknown>
controller-manager <unknown>
etcd-1 <unknown>
etcd-2 <unknown>
etcd-0 <unknown>
- Kubernetes 1.16.6 存在 Bugs 导致返回结果一直为
<unknown>
,但kubectl get cs -o yaml
可以返回正确结果;
检查 kube-apiserver 监听的端口
[root@k8s-01 ~]# netstat -lnpt|grep kube-apiserve
tcp 0 0 192.168.200.11:6443 0.0.0.0:* LISTEN 15025/kube-apiserve
- 6443: 接收 https 请求的安全端口,对所有请求做认证和授权;
- 由于关闭了非安全端口,故没有监听 8080;
6.3 部署高可用 kube-controller-manager 集群
本文档介绍部署高可用 kube-controller-manager 集群的步骤。
该集群包含 3 个节点,启动后将通过竞争选举机制产生一个 leader 节点,其它节点为阻塞状态。当 leader 节点不可用时,阻塞的节点将再次进行选举产生新的 leader 节点,从而保证服务的可用性。
为保证通信安全,本文档先生成 x509 证书和私钥,kube-controller-manager 在如下两种情况下使用该证书:
- 与 kube-apiserver 的安全端口通信;
- 在安全端口(https,10252) 输出 prometheus 格式的 metrics;
6.3.1 创建 kube-controller-manager 证书和私钥
创建证书签名请求:
[root@k8s-01 ~]# cat > kube-controller-manager-csr.json <<EOF
{
"CN": "system:kube-controller-manager",
"key": {
"algo": "rsa",
"size": 2048
},
"hosts": [
"127.0.0.1",
"192.168.200.11",
"192.168.200.12",
"192.168.200.13"
],
"names": [
{
"C": "CN",
"ST": "BeiJing",
"L": "BeiJing",
"O": "system:kube-controller-manager",
"OU": "System"
}
]
}
EOF
- hosts 列表包含所有 kube-controller-manager 节点 IP;
- CN 和 O 均为
system:kube-controller-manager
,kubernetes 内置的 ClusterRoleBindingssystem:kube-controller-manager
赋予 kube-controller-manager 工作所需的权限。
生成证书和私钥:
[root@k8s-01 ~]# cfssl gencert -ca=/etc/kubernetes/ssl/ca.pem \
-ca-key=/etc/kubernetes/ssl/ca-key.pem \
-config=/etc/kubernetes/ssl/ca-config.json \
-profile=kubernetes kube-controller-manager-csr.json | cfssljson -bare kube-controller-manager
将生成的证书和私钥分发到所有 master 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp kube-controller-manager*.pem root@${node_ip}:/etc/kubernetes/ssl/
done
6.3.2 创建和分发 kubeconfig 文件
kube-controller-manager 使用 kubeconfig 文件访问 apiserver,该文件提供了 apiserver 地址、嵌入的 CA 证书和 kube-controller-manager 证书等信息:
[root@k8s-01 ~]# kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/ssl/ca.pem \
--embed-certs=true \
--server="https://##NODE_IP##:6443" \
--kubeconfig=kube-controller-manager.kubeconfig
[root@k8s-01 ~]# kubectl config set-credentials system:kube-controller-manager \
--client-certificate=/etc/kubernetes/ssl/kube-controller-manager.pem \
--client-key=/etc/kubernetes/ssl/kube-controller-manager-key.pem \
--embed-certs=true \
--kubeconfig=kube-controller-manager.kubeconfig
[root@k8s-01 ~]# kubectl config set-context system:kube-controller-manager \
--cluster=kubernetes \
--user=system:kube-controller-manager \
--kubeconfig=kube-controller-manager.kubeconfig
[root@k8s-01 ~]# kubectl config use-context system:kube-controller-manager --kubeconfig=kube-controller-manager.kubeconfig
- kube-controller-manager 与 kube-apiserver 混布,故直接通过节点 IP 访问 kube-apiserver;
分发 kubeconfig 到所有 master 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
sed -e "s/##NODE_IP##/${node_ip}/" kube-controller-manager.kubeconfig > kube-controller-manager-${node_ip}.kubeconfig
ssh root@${node_ip} "mkdir -p /etc/kubernetes/conf"
scp kube-controller-manager-${node_ip}.kubeconfig root@${node_ip}:/etc/kubernetes/conf/kube-controller-manager.kubeconfig
done
6.3.3 创建 kube-controller-manager systemd unit 模板文件
[root@k8s-01 ~]# cat > kube-controller-manager.service.template <<EOF
[Unit]
Description=Kubernetes Controller Manager
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
[Service]
WorkingDirectory=${K8S_DIR}/kube-controller-manager
ExecStart=/usr/k8s/bin/kube-controller-manager \\
--profiling \\
--cluster-name=kubernetes \\
--controllers=*,bootstrapsigner,tokencleaner \\
--kube-api-qps=1000 \\
--kube-api-burst=2000 \\
--leader-elect \\
--use-service-account-credentials\\
--concurrent-service-syncs=2 \\
--bind-address=##NODE_IP## \\
--secure-port=10252 \\
--tls-cert-file=/etc/kubernetes/ssl/kube-controller-manager.pem \\
--tls-private-key-file=/etc/kubernetes/ssl/kube-controller-manager-key.pem \\
--port=0 \\
--authentication-kubeconfig=/etc/kubernetes/conf/kube-controller-manager.kubeconfig \\
--client-ca-file=/etc/kubernetes/ssl/ca.pem \\
--requestheader-allowed-names="aggregator" \\
--requestheader-client-ca-file=/etc/kubernetes/ssl/ca.pem \\
--requestheader-extra-headers-prefix="X-Remote-Extra-" \\
--requestheader-group-headers=X-Remote-Group \\
--requestheader-username-headers=X-Remote-User \\
--authorization-kubeconfig=/etc/kubernetes/conf/kube-controller-manager.kubeconfig \\
--cluster-signing-cert-file=/etc/kubernetes/ssl/ca.pem \\
--cluster-signing-key-file=/etc/kubernetes/ssl/ca-key.pem \\
--experimental-cluster-signing-duration=876000h \\
--horizontal-pod-autoscaler-sync-period=10s \\
--concurrent-deployment-syncs=10 \\
--concurrent-gc-syncs=30 \\
--node-cidr-mask-size=24 \\
--service-cluster-ip-range=${SERVICE_CIDR} \\
--pod-eviction-timeout=6m \\
--terminated-pod-gc-threshold=10000 \\
--root-ca-file=/etc/kubernetes/ssl/ca.pem \\
--service-account-private-key-file=/etc/kubernetes/ssl/ca-key.pem \\
--kubeconfig=/etc/kubernetes/conf/kube-controller-manager.kubeconfig \\
--logtostderr=true \\
--v=2
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
EOF
--port=0
:关闭监听非安全端口(http),同时--address
参数无效,--bind-address
参数有效;--secure-port=10252
、--bind-address=0.0.0.0
: 在所有网络接口监听 10252 端口的 https /metrics 请求;--kubeconfig
:指定 kubeconfig 文件路径,kube-controller-manager 使用它连接和验证 kube-apiserver;--authentication-kubeconfig
和--authorization-kubeconfig
:kube-controller-manager 使用它连接 apiserver,对 client 的请求进行认证和授权。kube-controller-manager 不再使用 --tls-ca-file 对请求 https metrics 的 Client 证书进行校验。如果没有配置这两个 kubeconfig 参数,则 client 连接 kube-controller-manager https 端口的请求会被拒绝(提示权限不足)。--cluster-signing-*-file
:签名 TLS Bootstrap 创建的证书;--experimental-cluster-signing-duration
:指定 TLS Bootstrap 证书的有效期;--root-ca-file
:放置到容器 ServiceAccount 中的 CA 证书,用来对 kube-apiserver 的证书进行校验;--service-account-private-key-file
:签名 ServiceAccount 中 Token 的私钥文件,必须和 kube-apiserver 的 --service-account-key-file 指定的公钥文件配对使用;--service-cluster-ip-range
:指定 Service Cluster IP 网段,必须和 kube-apiserver 中的同名参数一致;--leader-elect=true
:集群运行模式,启用选举功能;被选为 leader 的节点负责处理工作,其它节点为阻塞状态;--controllers=*,bootstrapsigner,tokencleaner
:启用的控制器列表,tokencleaner 用于自动清理过期的 Bootstrap token;--horizontal-pod-autoscaler-*
:custom metrics 相关参数,支持 autoscaling/v2alpha1;--tls-cert-file、--tls-private-key-file
:使用 https 输出 metrics 时使用的 Server 证书和秘钥;--use-service-account-credentials=true
: kube-controller-manager 中各 controller 使用 serviceaccount 访问 kube-apiserver;
6.3.4 为各节点创建和分发 kube-controller-mananger systemd unit 文件
替换模板文件中的变量,为各节点创建 systemd unit 文件:
[root@k8s-01 ~]# for (( i=0; i < 3; i++ ))
do
sed -e "s/##NODE_NAME##/${NODE_NAMES[i]}/" -e "s/##NODE_IP##/${NODE_IPS[i]}/" kube-controller-manager.service.template > kube-controller-manager-${NODE_IPS[i]}.service
done
分发到所有 master 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp kube-controller-manager-${node_ip}.service root@${node_ip}:/etc/systemd/system/kube-controller-manager.service
done
6.3.5 启动 kube-controller-manager 服务
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p ${K8S_DIR}/kube-controller-manager"
ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-controller-manager && systemctl restart kube-controller-manager"
done
检查服务运行状态
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "systemctl status kube-controller-manager|grep Active"
done
确保状态为 active (running)
,否则查看日志,确认原因:
journalctl -u kube-controller-manager
kube-controller-manager 监听 10252 端口,接收 https 请求:
[root@k8s-01 ~]# netstat -lnpt | grep kube-controll
tcp 0 0 192.168.200.11:10252 0.0.0.0:* LISTEN 15263/kube-controll
查看输出的 metrics
注意:以下命令在 kube-controller-manager 节点上执行。
[root@k8s-01 ~]# curl -s --cacert /etc/kubernetes/ssl/ca.pem --cert /etc/kubernetes/ssl/admin.pem --key /etc/kubernetes/ssl/admin-key.pem https://192.168.200.11:10252/metrics |head
# HELP apiserver_audit_event_total [ALPHA] Counter of audit events generated and sent to the audit backend.
# TYPE apiserver_audit_event_total counter
apiserver_audit_event_total 0
# HELP apiserver_audit_requests_rejected_total [ALPHA] Counter of apiserver requests rejected due to an error in audit logging backend.
# TYPE apiserver_audit_requests_rejected_total counter
apiserver_audit_requests_rejected_total 0
# HELP apiserver_client_certificate_expiration_seconds [ALPHA] Distribution of the remaining lifetime on the certificate used to authenticate a request.
# TYPE apiserver_client_certificate_expiration_seconds histogram
apiserver_client_certificate_expiration_seconds_bucket{le="0"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="1800"} 0
查看当前的 leader
[root@k8s-01 ~]# kubectl get endpoints kube-controller-manager --namespace=kube-system -o yaml
apiVersion: v1
kind: Endpoints
metadata:
annotations:
control-plane.alpha.kubernetes.io/leader: '{"holderIdentity":"k8s-02_ed2f8ea0-72a0-4755-88b4-cfa46ac3f9d8","leaseDurationSeconds":15,"acquireTime":"2023-04-26T07:15:32Z","renewTime":"2023-04-26T07:16:39Z","leaderTransitions":0}'
creationTimestamp: "2023-04-26T07:15:32Z"
name: kube-controller-manager
namespace: kube-system
resourceVersion: "377"
selfLink: /api/v1/namespaces/kube-system/endpoints/kube-controller-manager
uid: a1cac585-0842-4607-b99c-0a7b37a7b5a4
可见,当前的 leader 为 k8s-02 节点。
测试 kube-controller-manager 集群的高可用
停掉一个或两个节点的 kube-controller-manager 服务,观察其它节点的日志,看是否获取了 leader 权限。
参考
- 关于 controller 权限和 use-service-account-credentials 参数:https://kubernetes/kubernetes#48208
- kubelet 认证和授权:https://kubernetes.io/docs/admin/kubelet-authentication-authorization/#kubelet-authorization
6.4 部署高可用 kube-scheduler 集群
本文档介绍部署高可用 kube-scheduler 集群的步骤。
该集群包含 3 个节点,启动后将通过竞争选举机制产生一个 leader 节点,其它节点为阻塞状态。当 leader 节点不可用后,剩余节点将再次进行选举产生新的 leader 节点,从而保证服务的可用性。
为保证通信安全,本文档先生成 x509 证书和私钥,kube-scheduler 在如下两种情况下使用该证书:
- 与 kube-apiserver 的安全端口通信;
- 在安全端口(https,10251) 输出 prometheus 格式的 metrics;
6.4.1 创建 kube-scheduler 证书和私钥
创建证书签名请求:
[root@k8s-01 ~]# cat > kube-scheduler-csr.json <<EOF
{
"CN": "system:kube-scheduler",
"hosts": [
"127.0.0.1",
"192.168.200.11",
"192.168.200.12",
"192.168.200.13"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"ST": "BeiJing",
"L": "BeiJing",
"O": "system:kube-scheduler",
"OU": "System"
}
]
}
EOF
- hosts 列表包含所有 kube-scheduler 节点 IP;
- CN 和 O 均为
system:kube-scheduler
,kubernetes 内置的 ClusterRoleBindingssystem:kube-scheduler
将赋予 kube-scheduler 工作所需的权限;
生成证书和私钥:
[root@k8s-01 ~]# cfssl gencert -ca=/etc/kubernetes/ssl/ca.pem \
-ca-key=/etc/kubernetes/ssl/ca-key.pem \
-config=/etc/kubernetes/ssl/ca-config.json \
-profile=kubernetes kube-scheduler-csr.json | cfssljson -bare kube-scheduler
将生成的证书和私钥分发到所有 master 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp kube-scheduler*.pem root@${node_ip}:/etc/kubernetes/ssl/
done
6.4.2 创建和分发 kubeconfig 文件
kube-scheduler 使用 kubeconfig 文件访问 apiserver,该文件提供了 apiserver 地址、嵌入的 CA 证书和 kube-scheduler 证书:
[root@k8s-01 ~]# kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/ssl/ca.pem \
--embed-certs=true \
--server="https://##NODE_IP##:6443" \
--kubeconfig=kube-scheduler.kubeconfig
[root@k8s-01 ~]# kubectl config set-credentials system:kube-scheduler \
--client-certificate=/etc/kubernetes/ssl/kube-scheduler.pem \
--client-key=/etc/kubernetes/ssl/kube-scheduler-key.pem \
--embed-certs=true \
--kubeconfig=kube-scheduler.kubeconfig
[root@k8s-01 ~]# kubectl config set-context system:kube-scheduler \
--cluster=kubernetes \
--user=system:kube-scheduler \
--kubeconfig=kube-scheduler.kubeconfig
[root@k8s-01 ~]# kubectl config use-context system:kube-scheduler --kubeconfig=kube-scheduler.kubeconfig
分发 kubeconfig 到所有 master 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
sed -e "s/##NODE_IP##/${node_ip}/" kube-scheduler.kubeconfig > kube-scheduler-${node_ip}.kubeconfig
scp kube-scheduler-${node_ip}.kubeconfig root@${node_ip}:/etc/kubernetes/conf/kube-scheduler.kubeconfig
done
6.4.3 创建 kube-scheduler 配置文件
[root@k8s-01 ~]# cat > kube-scheduler.yaml.template <<EOF
apiVersion: kubescheduler.config.k8s.io/v1alpha1
kind: KubeSchedulerConfiguration
bindTimeoutSeconds: 600
clientConnection:
burst: 200
kubeconfig: "/etc/kubernetes/conf/kube-scheduler.kubeconfig"
qps: 100
enableContentionProfiling: false
enableProfiling: true
hardPodAffinitySymmetricWeight: 1
healthzBindAddress: ##NODE_IP##:10251
leaderElection:
leaderElect: true
metricsBindAddress: ##NODE_IP##:10251
EOF
--kubeconfig
:指定 kubeconfig 文件路径,kube-scheduler 使用它连接和验证 kube-apiserver;--leader-elect=true
:集群运行模式,启用选举功能;被选为 leader 的节点负责处理工作,其它节点为阻塞状态;
替换模板文件中的变量:
[root@k8s-01 ~]# for (( i=0; i < 3; i++ ))
do
sed -e "s/##NODE_NAME##/${NODE_NAMES[i]}/" -e "s/##NODE_IP##/${NODE_IPS[i]}/" kube-scheduler.yaml.template > kube-scheduler-${NODE_IPS[i]}.yaml
done
- NODE_NAMES 和 NODE_IPS 为相同长度的 bash 数组,分别为节点名称和对应的 IP;
分发 kube-scheduler 配置文件到所有 master 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp kube-scheduler-${node_ip}.yaml root@${node_ip}:/etc/kubernetes/work/kube-scheduler.yaml
done
- 重命名为 kube-scheduler.yaml;
6.4.4 创建 kube-scheduler systemd unit 模板文件
[root@k8s-01 ~]# cat > kube-scheduler.service.template <<EOF
[Unit]
Description=Kubernetes Scheduler
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
[Service]
WorkingDirectory=${K8S_DIR}/kube-scheduler
ExecStart=/usr/k8s/bin/kube-scheduler \\
--config=/etc/kubernetes/work/kube-scheduler.yaml \\
--bind-address=##NODE_IP## \\
--secure-port=10259 \\
--port=0 \\
--tls-cert-file=/etc/kubernetes/ssl/kube-scheduler.pem \\
--tls-private-key-file=/etc/kubernetes/ssl/kube-scheduler-key.pem \\
--authentication-kubeconfig=/etc/kubernetes/conf/kube-scheduler.kubeconfig \\
--client-ca-file=/etc/kubernetes/ssl/ca.pem \\
--requestheader-allowed-names="" \\
--requestheader-client-ca-file=/etc/kubernetes/ssl/ca.pem \\
--requestheader-extra-headers-prefix="X-Remote-Extra-" \\
--requestheader-group-headers=X-Remote-Group \\
--requestheader-username-headers=X-Remote-User \\
--authorization-kubeconfig=/etc/kubernetes/conf/kube-scheduler.kubeconfig \\
--logtostderr=true \\
--v=2
Restart=always
RestartSec=5
StartLimitInterval=0
[Install]
WantedBy=multi-user.target
EOF
6.4.5 为各节点创建和分发 kube-scheduler systemd unit 文件
替换模板文件中的变量,为各节点创建 systemd unit 文件:
[root@k8s-01 ~]# for (( i=0; i < 3; i++ ))
do
sed -e "s/##NODE_NAME##/${NODE_NAMES[i]}/" -e "s/##NODE_IP##/${NODE_IPS[i]}/" kube-scheduler.service.template > kube-scheduler-${NODE_IPS[i]}.service
done
分发 systemd unit 文件到所有 master 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp kube-scheduler-${node_ip}.service root@${node_ip}:/etc/systemd/system/kube-scheduler.service
done
6.4.6 启动 kube-scheduler 服务
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p ${K8S_DIR}/kube-scheduler"
ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-scheduler && systemctl restart kube-scheduler"
done
检查服务运行状态
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "systemctl status kube-scheduler|grep Active"
done
确保状态为 active (running)
,否则查看日志,确认原因:
journalctl -u kube-scheduler
查看输出的 metrics
注意:以下命令在 kube-scheduler 节点上执行。
kube-scheduler 监听 10251 和 10259 端口:
- 10251:接收 http 请求,非安全端口,不需要认证授权;
- 10259:接收 https 请求,安全端口,需要认证授权;
两个接口都对外提供 /metrics
和 /healthz
的访问。
[root@k8s-01 ~]# netstat -lnpt |grep kube-schedule
tcp 0 0 192.168.200.11:10251 0.0.0.0:* LISTEN 15487/kube-schedule
tcp 0 0 192.168.200.11:10259 0.0.0.0:* LISTEN 15487/kube-schedule
[root@k8s-01 ~]# curl -s http://192.168.200.11:10251/metrics |head
# HELP apiserver_audit_event_total [ALPHA] Counter of audit events generated and sent to the audit backend.
# TYPE apiserver_audit_event_total counter
apiserver_audit_event_total 0
# HELP apiserver_audit_requests_rejected_total [ALPHA] Counter of apiserver requests rejected due to an error in audit logging backend.
# TYPE apiserver_audit_requests_rejected_total counter
apiserver_audit_requests_rejected_total 0
# HELP apiserver_client_certificate_expiration_seconds [ALPHA] Distribution of the remaining lifetime on the certificate used to authenticate a request.
# TYPE apiserver_client_certificate_expiration_seconds histogram
apiserver_client_certificate_expiration_seconds_bucket{le="0"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="1800"} 0
[root@k8s-01 ~]# curl -s --cacert /etc/kubernetes/ssl/ca.pem --cert /etc/kubernetes/ssl/admin.pem --key /etc/kubernetes/ssl/admin-key.pem https://192.168.200.11:10259/metrics |head
# HELP apiserver_audit_event_total [ALPHA] Counter of audit events generated and sent to the audit backend.
# TYPE apiserver_audit_event_total counter
apiserver_audit_event_total 0
# HELP apiserver_audit_requests_rejected_total [ALPHA] Counter of apiserver requests rejected due to an error in audit logging backend.
# TYPE apiserver_audit_requests_rejected_total counter
apiserver_audit_requests_rejected_total 0
# HELP apiserver_client_certificate_expiration_seconds [ALPHA] Distribution of the remaining lifetime on the certificate used to authenticate a request.
# TYPE apiserver_client_certificate_expiration_seconds histogram
apiserver_client_certificate_expiration_seconds_bucket{le="0"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="1800"} 0
查看当前的 leader
[root@k8s-01 ~]# kubectl get endpoints kube-scheduler --namespace=kube-system -o yaml
apiVersion: v1
kind: Endpoints
metadata:
annotations:
control-plane.alpha.kubernetes.io/leader: '{"holderIdentity":"k8s-01_442adeb1-c418-413a-ad48-f6fa7e707ea9","leaseDurationSeconds":15,"acquireTime":"2023-04-26T07:19:27Z","renewTime":"2023-04-26T07:20:31Z","leaderTransitions":0}'
creationTimestamp: "2023-04-26T07:19:27Z"
name: kube-scheduler
namespace: kube-system
resourceVersion: "596"
selfLink: /api/v1/namespaces/kube-system/endpoints/kube-scheduler
uid: ab307246-466e-44df-b53c-78e5965b37a1
可见,当前的 leader 为 k8s-01 节点。
测试 kube-scheduler 集群的高可用
随便找一个或两个 master 节点,停掉 kube-scheduler 服务,看其它节点是否获取了 leader 权限。
7.6.2 查看 calico 运行状态
[root@k8s-01 ~]# kubectl get pods -n kube-system -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
calico-kube-controllers-59b699859f-rbllz 1/1 Running 0 108s 172.30.61.194 k8s-01 <none> <none>
calico-node-2mxnb 1/1 Running 0 108s 192.168.200.11 k8s-01 <none> <none>
calico-node-6bnm8 1/1 Running 0 108s 192.168.200.13 k8s-03 <none> <none>
calico-node-jdsxq 1/1 Running 0 108s 192.168.200.12 k8s-02 <none> <none>
使用 crictl 命令查看 calico 使用的镜像:
[root@k8s-01 ~]# crictl images | grep calico
docker.io/calico/cni v3.12.3 a6b30a97efd99 114MB
docker.io/calico/kube-controllers v3.12.3 77efab4f775c2 23.1MB
docker.io/calico/node v3.12.3 442f085df7b75 89.7MB
docker.io/calico/pod2daemon-flexvol v3.12.3 bfa72d71ec583 9.37MB
- 如果 crictl 输出为空或执行失败,则有可能是缺少配置文件
/etc/crictl.yaml
导致的,该文件的配置如下:
[root@k8s-01 ~]# cat /etc/crictl.yaml
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 10
debug: false
7、部署 worker 节点
7.1 安装依赖包
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "yum install -y epel-release" &
ssh root@${node_ip} "yum install -y chrony conntrack ipvsadm ipset jq iptables curl sysstat libseccomp wget socat git" &
done
7.2 apiserver 高可用
本文档讲解使用 nginx 4 层透明代理功能实现 Kubernetes worker 节点组件高可用访问 kube-apiserver 集群的步骤。
7.2.1 基于 nginx 代理的 kube-apiserver 高可用方案
- 控制节点的 kube-controller-manager、kube-scheduler 是多实例部署且连接本机的 kube-apiserver,所以只要有一个实例正常,就可以保证高可用;
- 集群内的 Pod 使用 K8S 服务域名 kubernetes 访问 kube-apiserver, kube-dns 会自动解析出多个 kube-apiserver 节点的 IP,所以也是高可用的;
- 在每个节点起一个 nginx 进程,后端对接多个 apiserver 实例,nginx 对它们做健康检查和负载均衡;
- kubelet、kube-proxy 通过本地的 nginx(监听 127.0.0.1)访问 kube-apiserver,从而实现 kube-apiserver 的高可用;
7.2.2 下载和编译 nginx
下载源码:
[root@k8s-01 ~]# wget http://nginx.org/download/nginx-1.15.3.tar.gz
[root@k8s-01 ~]# tar xf nginx-1.15.3.tar.gz
配置编译参数:
[root@k8s-01 ~]# cd nginx-1.15.3
[root@k8s-01 nginx-1.15.3]# mkdir nginx-prefix
[root@k8s-01 nginx-1.15.3]# ./configure --with-stream --without-http --prefix=$(pwd)/nginx-prefix --without-http_uwsgi_module --without-http_scgi_module --without-http_fastcgi_module
--with-stream
:开启 4 层透明转发(TCP Proxy)功能;--without-xxx
:关闭所有其他功能,这样生成的动态链接二进制程序依赖最小;
输出:
......
Configuration summary
+ PCRE library is not used
+ OpenSSL library is not used
+ zlib library is not used
nginx path prefix: "/root/nginx-1.15.3/nginx-prefix"
nginx binary file: "/root/nginx-1.15.3/nginx-prefix/sbin/nginx"
nginx modules path: "/root/nginx-1.15.3/nginx-prefix/modules"
nginx configuration prefix: "/root/nginx-1.15.3/nginx-prefix/conf"
nginx configuration file: "/root/nginx-1.15.3/nginx-prefix/conf/nginx.conf"
nginx pid file: "/root/nginx-1.15.3/nginx-prefix/logs/nginx.pid"
nginx error log file: "/root/nginx-1.15.3/nginx-prefix/logs/error.log"
nginx http access log file: "/root/nginx-1.15.3/nginx-prefix/logs/access.log"
nginx http client request body temporary files: "client_body_temp"
nginx http proxy temporary files: "proxy_temp"
编译和安装:
[root@k8s-01 nginx-1.15.3]# make && make install
7.2.3 验证编译的 nginx
[root@k8s-01 nginx-1.15.3]# ./nginx-prefix/sbin/nginx -v
nginx version: nginx/1.15.3
7.2.4 安装和部署 nginx
拷贝二进制程序:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p /usr/k8s/kube-nginx/{conf,logs,sbin}"
scp nginx-prefix/sbin/nginx root@${node_ip}:/usr/k8s/kube-nginx/sbin/kube-nginx
ssh root@${node_ip} "chmod a+x /usr/k8s/kube-nginx/sbin/*"
done
- 重命名二进制文件为 kube-nginx;
配置 nginx,开启 4 层透明转发功能:
[root@k8s-01 ~]# cat > kube-nginx.conf <<EOF
worker_processes 1;
events {
worker_connections 1024;
}
stream {
upstream backend {
hash $remote_addr consistent;
server 192.168.200.11:6443 max_fails=3 fail_timeout=30s;
server 192.168.200.12:6443 max_fails=3 fail_timeout=30s;
server 192.168.200.13:6443 max_fails=3 fail_timeout=30s;
}
server {
listen 127.0.0.1:8443;
proxy_connect_timeout 1s;
proxy_pass backend;
}
}
EOF
upstream backend
中的 server 列表为集群中各 kube-apiserver 的节点 IP,需要根据实际情况修改;
分发配置文件:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp kube-nginx.conf root@${node_ip}:/usr/k8s/kube-nginx/conf/kube-nginx.conf
done
7.2.5 配置 systemd unit 文件,启动服务
配置 kube-nginx systemd unit 文件:
[root@k8s-01 ~]# cat > kube-nginx.service <<EOF
[Unit]
Description=kube-apiserver nginx proxy
After=network.target
After=network-online.target
Wants=network-online.target
[Service]
Type=forking
ExecStartPre=/usr/k8s/kube-nginx/sbin/kube-nginx -c /usr/k8s/kube-nginx/conf/kube-nginx.conf -p /usr/k8s/kube-nginx -t
ExecStart=/usr/k8s/kube-nginx/sbin/kube-nginx -c /usr/k8s/kube-nginx/conf/kube-nginx.conf -p /usr/k8s/kube-nginx
ExecReload=/usr/k8s/kube-nginx/sbin/kube-nginx -c /usr/k8s/kube-nginx/conf/kube-nginx.conf -p /usr/k8s/kube-nginx -s reload
PrivateTmp=true
Restart=always
RestartSec=5
StartLimitInterval=0
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
分发 systemd unit 文件:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp kube-nginx.service root@${node_ip}:/etc/systemd/system/
done
启动 kube-nginx 服务:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-nginx && systemctl restart kube-nginx"
done
7.2.6 检查 kube-nginx 服务运行状态
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "systemctl status kube-nginx |grep 'Active:'"
done
确保状态为 active (running),否则查看日志,确认原因:
journalctl -u kube-nginx
7.3 部署 containerd 组件
containerd 实现了 kubernetes 的 Container Runtime Interface (CRI) 接口,提供容器运行时核心功能,如镜像管理、容器管理等,相比 dockerd 更加简单、健壮和可移植。
注意:
- 如果想使用 docker,请参考附件 F.部署docker.md;
- docker 需要与 flannel 配合使用,且先安装 flannel;
7.3.1 下载和分发二进制文件
下载二进制文件:
[root@k8s-01 ~]# wget https://github.com/kubernetes-sigs/cri-tools/releases/download/v1.17.0/crictl-v1.17.0-linux-amd64.tar.gz \
https://github.com/opencontainers/runc/releases/download/v1.0.0-rc10/runc.amd64 \
https://github.com/containernetworking/plugins/releases/download/v0.8.5/cni-plugins-linux-amd64-v0.8.5.tgz \
https://github.com/containerd/containerd/releases/download/v1.3.3/containerd-1.3.3.linux-amd64.tar.gz
解压:
[root@k8s-01 ~]# mkdir containerd
[root@k8s-01 ~]# tar xf containerd-1.3.3.linux-amd64.tar.gz -C containerd/
[root@k8s-01 ~]# tar xf crictl-v1.17.0-linux-amd64.tar.gz
[root@k8s-01 ~]# mkdir cni-plugins
[root@k8s-01 ~]# tar xf cni-plugins-linux-amd64-v0.8.5.tgz -C cni-plugins/
[root@k8s-01 ~]# mv runc.amd64 runc
分发二进制文件到所有 worker 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp containerd/bin/* crictl cni-plugins/* runc root@${node_ip}:/usr/k8s/bin
ssh root@${node_ip} "chmod a+x /usr/k8s/bin/* && mkdir -p /etc/cni/net.d"
done
7.3.2 创建和分发 containerd 配置文件
[root@k8s-01 ~]# cat > containerd-config.toml <<EOF
version = 2
root = "${CONTAINERD_DIR}/root"
state = "${CONTAINERD_DIR}/state"
[plugins]
[plugins."io.containerd.grpc.v1.cri"]
sandbox_image = "registry.cn-beijing.aliyuncs.com/zhoujun/pause-amd64:3.1"
[plugins."io.containerd.grpc.v1.cri".cni]
bin_dir = "/usr/k8s/bin"
conf_dir = "/etc/cni/net.d"
[plugins."io.containerd.runtime.v1.linux"]
shim = "containerd-shim"
runtime = "runc"
runtime_root = ""
no_shim = false
shim_debug = false
EOF
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p /etc/containerd/${CONTAINERD_DIR}/{root,state}"
scp containerd-config.toml root@${node_ip}:/etc/containerd/config.toml
done
7.3.3 创建 containerd systemd unit 文件
[root@k8s-01 ~]# cat > containerd.service <<EOF
[Unit]
Description=containerd container runtime
Documentation=https://containerd.io
After=network.target
[Service]
Environment="PATH=/usr/k8s/bin:/bin:/sbin:/usr/bin:/usr/sbin"
ExecStartPre=/sbin/modprobe overlay
ExecStart=/usr/k8s/bin/containerd
Restart=always
RestartSec=5
Delegate=yes
KillMode=process
OOMScoreAdjust=-999
LimitNOFILE=1048576
LimitNPROC=infinity
LimitCORE=infinity
[Install]
WantedBy=multi-user.target
EOF
7.3.4 分发 systemd unit 文件,启动 containerd 服务
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp containerd.service root@${node_ip}:/etc/systemd/system
ssh root@${node_ip} "systemctl enable containerd && systemctl restart containerd"
done
7.3.5 创建和分发 crictl 配置文件
crictl 是兼容 CRI 容器运行时的命令行工具,提供类似于 docker 命令的功能。具体参考官方文档。
[root@k8s-01 ~]# cat > crictl.yaml <<EOF
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 10
debug: false
EOF
分发到所有 worker 节点:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
scp crictl.yaml root@${node_ip}:/etc/crictl.yaml
done
7.4 部署 kubelet 组件
kubelet 运行在每个 worker 节点上,接收 kube-apiserver 发送的请求,管理 Pod 容器,执行交互式命令,如 exec、run、logs 等。
kubelet 启动时自动向 kube-apiserver 注册节点信息,内置的 cadvisor 统计和监控节点的资源使用情况。
为确保安全,部署时关闭了 kubelet 的非安全 http 端口,对请求进行认证和授权,拒绝未授权的访问(如 apiserver、heapster 的请求)。
7.4.1 创建 kubelet bootstrap kubeconfig 文件
[root@k8s-01 ~]# for node_name in ${NODE_NAMES[@]}
do
echo ">>> ${node_name}"
# 创建 token
export BOOTSTRAP_TOKEN=$(kubeadm token create \
--description kubelet-bootstrap-token \
--groups system:bootstrappers:${node_name} \
--kubeconfig ~/.kube/config)
# 设置集群参数
kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/ssl/ca.pem \
--embed-certs=true \
--server=${KUBE_APISERVER} \
--kubeconfig=kubelet-bootstrap-${node_name}.kubeconfig
# 设置客户端认证参数
kubectl config set-credentials kubelet-bootstrap \
--token=${BOOTSTRAP_TOKEN} \
--kubeconfig=kubelet-bootstrap-${node_name}.kubeconfig
# 设置上下文参数
kubectl config set-context default \
--cluster=kubernetes \
--user=kubelet-bootstrap \
--kubeconfig=kubelet-bootstrap-${node_name}.kubeconfig
# 设置默认上下文
kubectl config use-context default --kubeconfig=kubelet-bootstrap-${node_name}.kubeconfig
done
- 向 kubeconfig 写入的是 token,bootstrap 结束后 kube-controller-manager 为 kubelet 创建 client 和 server 证书;
查看 kubeadm 为各节点创建的 token:
[root@k8s-01 ~]# kubeadm token list --kubeconfig ~/.kube/config
TOKEN TTL EXPIRES USAGES DESCRIPTION EXTRA GROUPS
199182.hjz2qix4fz012u9g 23h 2023-04-27T15:28:09+08:00 authentication,signing kubelet-bootstrap-token system:bootstrappers:k8s-02
2srxhw.m00g0vewzu3froia 23h 2023-04-27T15:28:09+08:00 authentication,signing kubelet-bootstrap-token system:bootstrappers:k8s-03
hkowyc.o2pl73d94q9uefsr 23h 2023-04-27T15:28:09+08:00 authentication,signing kubelet-bootstrap-token system:bootstrappers:k8s-01
- token 有效期为 1 天,超期后将不能再被用来 boostrap kubelet,且会被 kube-controller-manager 的 tokencleaner 清理;
- kube-apiserver 接收 kubelet 的 bootstrap token 后,将请求的 user 设置为
system:bootstrap:<Token ID>
,group 设置为system:bootstrappers
,后续将为这个 group 设置 ClusterRoleBinding;
7.4.2 分发 bootstrap kubeconfig 文件到所有 worker 节点
[root@k8s-01 ~]# for node_name in ${NODE_NAMES[@]}
do
echo ">>> ${node_name}"
scp kubelet-bootstrap-${node_name}.kubeconfig root@${node_name}:/etc/kubernetes/conf/kubelet-bootstrap.kubeconfig
done
7.4.3 创建和分发 kubelet 参数配置文件
从 v1.10 开始,部分 kubelet 参数需在配置文件中配置,kubelet --help
会提示:
DEPRECATED: This parameter should be set via the config file specified by the Kubelet's --config flag
创建 kubelet 参数配置文件模板(可配置项参考代码中注释):
[root@k8s-01 ~]# cat > kubelet-config.yaml.template <<EOF
kind: KubeletConfiguration
apiVersion: kubelet.config.k8s.io/v1beta1
address: "##NODE_IP##"
staticPodPath: ""
syncFrequency: 1m
fileCheckFrequency: 20s
httpCheckFrequency: 20s
staticPodURL: ""
port: 10250
readOnlyPort: 0
rotateCertificates: true
serverTLSBootstrap: true
authentication:
anonymous:
enabled: false
webhook:
enabled: true
x509:
clientCAFile: "/etc/kubernetes/ssl/ca.pem"
authorization:
mode: Webhook
registryPullQPS: 0
registryBurst: 20
eventRecordQPS: 0
eventBurst: 20
enableDebuggingHandlers: true
enableContentionProfiling: true
healthzPort: 10248
healthzBindAddress: "##NODE_IP##"
clusterDomain: "${CLUSTER_DNS_DOMAIN}"
clusterDNS:
- "${CLUSTER_DNS_SVC_IP}"
nodeStatusUpdateFrequency: 10s
nodeStatusReportFrequency: 1m
imageMinimumGCAge: 2m
imageGCHighThresholdPercent: 85
imageGCLowThresholdPercent: 80
volumeStatsAggPeriod: 1m
kubeletCgroups: ""
systemCgroups: ""
cgroupRoot: ""
cgroupsPerQOS: true
cgroupDriver: cgroupfs
runtimeRequestTimeout: 10m
hairpinMode: promiscuous-bridge
maxPods: 220
podCIDR: "${CLUSTER_CIDR}"
podPidsLimit: -1
resolvConf: /etc/resolv.conf
maxOpenFiles: 1000000
kubeAPIQPS: 1000
kubeAPIBurst: 2000
serializeImagePulls: false
evictionHard:
memory.available: "100Mi"
nodefs.available: "10%"
nodefs.inodesFree: "5%"
imagefs.available: "15%"
evictionSoft: {}
enableControllerAttachDetach: true
failSwapOn: true
containerLogMaxSize: 20Mi
containerLogMaxFiles: 10
systemReserved: {}
kubeReserved: {}
systemReservedCgroup: ""
kubeReservedCgroup: ""
enforceNodeAllocatable: ["pods"]
EOF
- address:kubelet 安全端口(https,10250)监听的地址,不能为 127.0.0.1,否则 kube-apiserver、heapster 等不能调用 kubelet 的 API;
- readOnlyPort=0:关闭只读端口(默认 10255),等效为未指定;
- authentication.anonymous.enabled:设置为 false,不允许匿名�访问 10250 端口;
- authentication.x509.clientCAFile:指定签名客户端证书的 CA 证书,开启 HTTP 证书认证;
- authentication.webhook.enabled=true:开启 HTTPs bearer token 认证;
- 对于未通过 x509 证书和 webhook 认证的请求(kube-apiserver 或其他客户端),将被拒绝,提示 Unauthorized;
- authroization.mode=Webhook:kubelet 使用 SubjectAccessReview API 查询 kube-apiserver 某 user、group 是否具有操作资源的权限(RBAC);
- featureGates.RotateKubeletClientCertificate、featureGates.RotateKubeletServerCertificate:自动 rotate 证书,证书的有效期取决于 kube-controller-manager 的 --experimental-cluster-signing-duration 参数;
- 需要 root 账户运行;
为各节点创建和分发 kubelet 配置文件:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
sed -e "s/##NODE_IP##/${node_ip}/" kubelet-config.yaml.template > kubelet-config-${node_ip}.yaml.template
scp kubelet-config-${node_ip}.yaml.template root@${node_ip}:/etc/kubernetes/work/kubelet-config.yaml
done
7.4.4 创建和分发 kubelet systemd unit 文件
创建 kubelet systemd unit 文件模板:
[root@k8s-01 ~]# cat > kubelet.service.template <<EOF
[Unit]
Description=Kubernetes Kubelet
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
After=containerd.service
Requires=containerd.service
[Service]
WorkingDirectory=${K8S_DIR}/kubelet
ExecStart=/usr/k8s/bin/kubelet \\
--bootstrap-kubeconfig=/etc/kubernetes/conf/kubelet-bootstrap.kubeconfig \\
--cert-dir=/etc/kubernetes/ssl \\
--network-plugin=cni \\
--cni-conf-dir=/etc/cni/net.d \\
--container-runtime=remote \\
--container-runtime-endpoint=unix:///var/run/containerd/containerd.sock \\
--root-dir=${K8S_DIR}/kubelet \\
--kubeconfig=/etc/kubernetes/conf/kubelet.kubeconfig \\
--config=/etc/kubernetes/work/kubelet-config.yaml \\
--hostname-override=##NODE_NAME## \\
--image-pull-progress-deadline=15m \\
--volume-plugin-dir=${K8S_DIR}/kubelet/kubelet-plugins/volume/exec/ \\
--logtostderr=true \\
--v=2
Restart=always
RestartSec=5
StartLimitInterval=0
[Install]
WantedBy=multi-user.target
EOF
- 如果设置了
--hostname-override
选项,则kube-proxy
也需要设置该选项,否则会出现找不到 Node 的情况;--bootstrap-kubeconfig
:指向 bootstrap kubeconfig 文件,kubelet 使用该文件中的用户名和 token 向 kube-apiserver 发送 TLS Bootstrapping 请求;- K8S approve kubelet 的 csr 请求后,在
--cert-dir
目录创建证书和私钥文件,然后写入--kubeconfig
文件;--pod-infra-container-image
不使用 redhat 的pod-infrastructure:latest
镜像,它不能回收容器的僵尸;
为各节点创建和分发 kubelet systemd unit 文件:
[root@k8s-01 ~]# for node_name in ${NODE_NAMES[@]}
do
echo ">>> ${node_name}"
ssh root@${node_ip} "mkdir -p ${K8S_DIR}/kubelet"
sed -e "s/##NODE_NAME##/${node_name}/" kubelet.service.template > kubelet-${node_name}.service
scp kubelet-${node_name}.service root@${node_name}:/etc/systemd/system/kubelet.service
done
7.4.5 授予 kube-apiserver 访问 kubelet API 的权限
在执行 kubectl exec、run、logs 等命令时,apiserver 会将请求转发到 kubelet 的 https 端口。这里定义 RBAC 规则,授权 apiserver 使用的证书(kubernetes.pem)用户名(CN:kuberntes-master)访问 kubelet API 的权限:
[root@k8s-01 ~]# kubectl create clusterrolebinding kube-apiserver:kubelet-apis --clusterrole=system:kubelet-api-admin --user kubernetes-master
7.4.6 Bootstrap Token Auth 和授予权限
kubelet 启动时查找 --kubeletconfig
参数对应的文件是否存在,如果不存在则使用 --bootstrap-kubeconfig
指定的 kubeconfig 文件向 kube-apiserver 发送证书签名请求 (CSR)。
kube-apiserver 收到 CSR 请求后,对其中的 Token 进行认证,认证通过后将请求的 user 设置为 system:bootstrap:<Token ID>
,group 设置为 system:bootstrappers
,这一过程称为 Bootstrap Token Auth
。
默认情况下,这个 user 和 group 没有创建 CSR 的权限,kubelet 启动失败,错误日志如下:
$ sudo journalctl -u kubelet -a |grep -A 2 'certificatesigningrequests'
May 26 12:13:41 k8s-01 kubelet[128468]: I0526 12:13:41.798230 128468 certificate_manager.go:366] Rotating certificates
May 26 12:13:41 k8s-01 kubelet[128468]: E0526 12:13:41.801997 128468 certificate_manager.go:385] Failed while requesting a signed certificate from the master: cannot create certificate signing request: certificatesigningrequests.certificates.k8s.io is forbidden: User "system:bootstrap:82jfrm" cannot create resource "certificatesigningrequests" in API group "certificates.k8s.io" at the cluster scope
解决办法是:创建一个 clusterrolebinding,将 group system:bootstrappers 和 clusterrole system:node-bootstrapper 绑定:
[root@k8s-01 ~]# kubectl create clusterrolebinding kubelet-bootstrap --clusterrole=system:node-bootstrapper --group=system:bootstrappers
7.4.7 自动 approve CSR 请求,生成 kubelet client 证书
kubelet 创建 CSR 请求后,下一步需要创建被 approve,有两种方式:
- kube-controller-manager 自动 aprrove;
- 手动使用命令
kubectl certificate approve
;
CSR 被 approve 后,kubelet 向 kube-controller-manager 请求创建 client 证书,kube-controller-manager 中的 csrapproving
controller 使用 SubjectAccessReview
API 来检查 kubelet 请求(对应的 group 是 system:bootstrappers)是否具有相应的权限。
创建三个 ClusterRoleBinding,分别授予 group system:bootstrappers 和 group system:nodes 进行 approve client、renew client、renew server 证书的权限(server csr 是手动 approve 的,见后文):
[root@k8s-01 ~]# cat > csr-crb.yaml <<EOF
# Approve all CSRs for the group "system:bootstrappers"
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: auto-approve-csrs-for-group
subjects:
- kind: Group
name: system:bootstrappers
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: system:certificates.k8s.io:certificatesigningrequests:nodeclient
apiGroup: rbac.authorization.k8s.io
---
# To let a node of the group "system:nodes" renew its own credentials
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: node-client-cert-renewal
subjects:
- kind: Group
name: system:nodes
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: system:certificates.k8s.io:certificatesigningrequests:selfnodeclient
apiGroup: rbac.authorization.k8s.io
---
# A ClusterRole which instructs the CSR approver to approve a node requesting a
# serving cert matching its client cert.
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: approve-node-server-renewal-csr
rules:
- apiGroups: ["certificates.k8s.io"]
resources: ["certificatesigningrequests/selfnodeserver"]
verbs: ["create"]
---
# To let a node of the group "system:nodes" renew its own server credentials
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: node-server-cert-renewal
subjects:
- kind: Group
name: system:nodes
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: approve-node-server-renewal-csr
apiGroup: rbac.authorization.k8s.io
EOF
[root@k8s-01 ~]# mv csr-crb.yaml /etc/kubernetes/work/
[root@k8s-01 ~]# kubectl apply -f /etc/kubernetes/work/csr-crb.yaml
- auto-approve-csrs-for-group:自动 approve node 的第一次 CSR; 注意第一次 CSR 时,请求的 Group 为 system:bootstrappers;
- node-client-cert-renewal:自动 approve node 后续过期的 client 证书,自动生成的证书 Group 为 system:nodes;
- node-server-cert-renewal:自动 approve node 后续过期的 server 证书,自动生成的证书 Group 为 system:nodes;
7.4.8 启动 kubelet 服务
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p ${K8S_DIR}/kubelet/kubelet-plugins/volume/exec/"
ssh root@${node_ip} "/usr/sbin/swapoff -a"
ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kubelet && systemctl restart kubelet"
done
- 启动服务前必须先创建工作目录;
- 关闭 swap 分区,否则 kubelet 会启动失败;
kubelet 启动后使用 --bootstrap-kubeconfig 向 kube-apiserver 发送 CSR 请求,当这个 CSR 被 approve 后,kube-controller-manager 为 kubelet 创建 TLS 客户端证书、私钥和 --kubeletconfig 文件。
注意:kube-controller-manager 需要配置 --cluster-signing-cert-file
和 --cluster-signing-key-file
参数,才会为 TLS Bootstrap 创建证书和私钥。
7.4.9 查看 kubelet 情况
稍等一会,三个节点的 CSR 都被自动 approved:
[root@k8s-01 ~]# kubectl get csr
NAME AGE REQUESTOR CONDITION
csr-8qtsv 21s system:bootstrap:hkowyc Approved,Issued
csr-fhw84 20s system:bootstrap:199182 Approved,Issued
csr-lktxp 4s system:node:k8s-02 Pending
csr-nrsg4 4s system:node:k8s-03 Pending
csr-qpgc4 5s system:node:k8s-01 Pending
csr-tln6r 20s system:bootstrap:2srxhw Approved,Issued
- Pending 的 CSR 用于创建 kubelet server 证书,需要手动 approve,参考后文。
所有节点均注册(NotReady 状态是预期的,后续安装了网络插件后就好):
[root@k8s-01 ~]# kubectl get node
NAME STATUS ROLES AGE VERSION
k8s-01 NotReady <none> 67s v1.16.6
k8s-02 NotReady <none> 66s v1.16.6
k8s-03 NotReady <none> 66s v1.16.6
kube-controller-manager 为各 node 生成了 kubeconfig 文件和公私钥:
[root@k8s-01 ~]# ls -l /etc/kubernetes/conf/kubelet.kubeconfig
-rw------- 1 root root 2232 4月 26 15:44 /etc/kubernetes/conf/kubelet.kubeconfig
[root@k8s-01 ~]# ls -l /etc/kubernetes/ssl/kubelet-client-*
-rw------- 1 root root 1269 4月 26 15:44 /etc/kubernetes/ssl/kubelet-client-2023-04-26-15-44-30.pem
lrwxrwxrwx 1 root root 58 4月 26 15:44 /etc/kubernetes/ssl/kubelet-client-current.pem -> /etc/kubernetes/ssl/kubelet-client-2023-04-26-15-44-30.pem
- 没有自动生成 kubelet server 证书;
7.4.10 手动 approve server cert csr
基于安全性考虑,CSR approving controllers 不会自动 approve kubelet server 证书签名请求,需要手动 approve:
# 手动 approve
[root@k8s-01 ~]# kubectl get csr | grep Pending | awk '{print $1}' | xargs kubectl certificate approve
# 自动生成了 server 证书
[root@k8s-01 ~]# ls -l /etc/kubernetes/ssl/kubelet-*
-rw------- 1 root root 1269 4月 26 15:44 /etc/kubernetes/ssl/kubelet-client-2023-04-26-15-44-30.pem
lrwxrwxrwx 1 root root 58 4月 26 15:44 /etc/kubernetes/ssl/kubelet-client-current.pem -> /etc/kubernetes/ssl/kubelet-client-2023-04-26-15-44-30.pem
-rw------- 1 root root 1305 4月 26 15:46 /etc/kubernetes/ssl/kubelet-server-2023-04-26-15-46-14.pem
lrwxrwxrwx 1 root root 58 4月 26 15:46 /etc/kubernetes/ssl/kubelet-server-current.pem -> /etc/kubernetes/ssl/kubelet-server-2023-04-26-15-46-14.pem
[root@k8s-01 ~]# kubectl get csr
NAME AGE REQUESTOR CONDITION
csr-8qtsv 109s system:bootstrap:hkowyc Approved,Issued
csr-fhw84 108s system:bootstrap:199182 Approved,Issued
csr-lktxp 92s system:node:k8s-02 Approved,Issued
csr-nrsg4 92s system:node:k8s-03 Approved,Issued
csr-qpgc4 93s system:node:k8s-01 Approved,Issued
csr-tln6r 108s system:bootstrap:2srxhw Approved,Issued
7.4.11 kubelet api 认证和授权
kubelet 配置了如下认证参数:
- authentication.anonymous.enabled:设置为 false,不允许匿名�访问 10250 端口;
- authentication.x509.clientCAFile:指定签名客户端证书的 CA 证书,开启 HTTPs 证书认证;
- authentication.webhook.enabled=true:开启 HTTPs bearer token 认证;
同时配置了如下授权参数:
- uthroization.mode=Webhook:开启 RBAC 授权;
kubelet 收到请求后,使用 clientCAFile 对证书签名进行认证,或者查询 bearer token 是否有效。如果两者都没通过,则拒绝请求,提示 Unauthorized
:
[root@k8s-01 ~]# curl -s --cacert /etc/kubernetes/ssl/ca.pem https://192.168.200.11:10250/metrics
Unauthorized
[root@k8s-01 ~]# curl -s --cacert /etc/kubernetes/ssl/ca.pem -H "Authorization: Bearer 123456" https://192.168.200.11:10250/metrics
Unauthorized
通过认证后,kubelet 使用 SubjectAccessReview API
向 kube-apiserver 发送请求,查询证书或 token 对应的 user、group 是否有操作资源的权限(RBAC);
7.4.12 证书认证和授权
# 权限不足的证书;
[root@k8s-01 ~]# curl -s --cacert /etc/kubernetes/ssl/ca.pem --cert /etc/kubernetes/ssl/kube-controller-manager.pem --key /etc/kubernetes/ssl/kube-controller-manager-key.pem https://192.168.200.11:10250/metrics
Forbidden (user=system:kube-controller-manager, verb=get, resource=nodes, subresource=metrics)
# 使用部署 kubectl 命令行工具时创建的、具有最高权限的 admin 证书;
[root@k8s-01 ~]# curl -s --cacert /etc/kubernetes/ssl/ca.pem --cert /etc/kubernetes/ssl/admin.pem --key /etc/kubernetes/ssl/admin-key.pem https://192.168.200.11:10250/metrics|head
# HELP apiserver_audit_event_total [ALPHA] Counter of audit events generated and sent to the audit backend.
# TYPE apiserver_audit_event_total counter
apiserver_audit_event_total 0
# HELP apiserver_audit_requests_rejected_total [ALPHA] Counter of apiserver requests rejected due to an error in audit logging backend.
# TYPE apiserver_audit_requests_rejected_total counter
apiserver_audit_requests_rejected_total 0
# HELP apiserver_client_certificate_expiration_seconds [ALPHA] Distribution of the remaining lifetime on the certificate used to authenticate a request.
# TYPE apiserver_client_certificate_expiration_seconds histogram
apiserver_client_certificate_expiration_seconds_bucket{le="0"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="1800"} 0
--cacert
、--cert
、--key
的参数值必须是文件路径,如上面的./admin.pem
不能省略./
,否则返回401 Unauthorized
;
7.4.13 bear token 认证和授权
创建一个 ServiceAccount,将它和 ClusterRole system:kubelet-api-admin 绑定,从而具有调用 kubelet API 的权限:
[root@k8s-01 ~]# kubectl create sa kubelet-api-test
[root@k8s-01 ~]# kubectl create clusterrolebinding kubelet-api-test --clusterrole=system:kubelet-api-admin --serviceaccount=default:kubelet-api-test
[root@k8s-01 ~]# SECRET=$(kubectl get secrets | grep kubelet-api-test | awk '{print $1}')
[root@k8s-01 ~]# TOKEN=$(kubectl describe secret ${SECRET} | grep -E '^token' | awk '{print $2}')
[root@k8s-01 ~]# echo ${TOKEN}
eyJhbGciOiJSUzI1NiIsImtpZCI6Im1tY0N4R0h6LXZqS0FXWlVOb0c3NWo5UEoxNXd5M0hKWmZHUFNFbl9MWjAifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6Imt1YmVsZXQtYXBpLXRlc3QtdG9rZW4tc2NtbjIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoia3ViZWxldC1hcGktdGVzdCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6ImM4ODYwMmQ3LTAwMDAtNDZlNi04OTI0LTc4NWQxZTViYjQ2OSIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0Omt1YmVsZXQtYXBpLXRlc3QifQ.K3TYmRBxZmVN6i0WbD9N4U3YqVREK5E4kuhRV5GmLyjsoov2mg7Ytsj57yGkYN7vG3115ibase3Tql6zkmpS9DrBBiyStnbzEkUq2bZTHcBWhZoSNuazVDtjXZ301VFzDoo4WQf-FzX2QM_2jsLl-23hlGecJXwrg0BxfYZb4s2Qzc_EYSywlsg3Hrkvkc2LQLiJSd8rXZ_jgHouJQQOYQc6AIUpxiUiwjYQHQLHoFgzI7CSa1HeMzd7mR9W9x6C-tqAZL39PaoVh8aYqoN-6lmmPS0xv19R68jjKELNZI2qhKI_Fnj5VLi7ivTNjr3qmMoHEX7p0zHumjBjwWXn_g
[root@k8s-01 ~]# curl -s --cacert /etc/kubernetes/ssl/ca.pem -H "Authorization: Bearer ${TOKEN}" https://192.168.200.11:10250/metrics | head
# HELP apiserver_audit_event_total [ALPHA] Counter of audit events generated and sent to the audit backend.
# TYPE apiserver_audit_event_total counter
apiserver_audit_event_total 0
# HELP apiserver_audit_requests_rejected_total [ALPHA] Counter of apiserver requests rejected due to an error in audit logging backend.
# TYPE apiserver_audit_requests_rejected_total counter
apiserver_audit_requests_rejected_total 0
# HELP apiserver_client_certificate_expiration_seconds [ALPHA] Distribution of the remaining lifetime on the certificate used to authenticate a request.
# TYPE apiserver_client_certificate_expiration_seconds histogram
apiserver_client_certificate_expiration_seconds_bucket{le="0"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="1800"} 0
7.4.14 cadvisor 和 metrics
cadvisor 是内嵌在 kubelet 二进制中的,统计所在节点各容器的资源(CPU、内存、磁盘、网卡)使用情况的服务。
浏览器访问 https://192.168.200.11:10250/metrics 和 https://192.168.200.11:10250/metrics/cadvisor 分别返回 kubelet 和 cadvisor 的 metrics。
注意:
- kubelet.config.json 设置 authentication.anonymous.enabled 为 false,不允许匿名证书访问 10250 的 https 服务;
- 参考A.浏览器访问kube-apiserver安全端口.md,创建和导入相关证书,然后访问上面的 10250 端口;
7.5 部署 kube-proxy 组件
kube-proxy 运行在所有 worker 节点上,它监听 apiserver 中 service 和 endpoint 的变化情况,创建路由规则以提供服务 IP 和负载均衡功能。
本文档讲解部署 ipvs 模式的 kube-proxy 过程。
7.5.1 创建 kube-proxy 证书
创建证书签名请求:
[root@k8s-01 ~]# cat > kube-proxy-csr.json <<EOF
{
"CN": "system:kube-proxy",
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"ST": "BeiJing",
"L": "BeiJing",
"O": "k8s",
"OU": "System"
}
]
}
EOF
- CN:指定该证书的 User 为
system:kube-proxy
;- 预定义的 RoleBinding
system:node-proxier
将Usersystem:kube-proxy
与 Rolesystem:node-proxier
绑定,该 Role 授予了调用kube-apiserver
Proxy 相关 API 的权限;- 该证书只会被 kube-proxy 当做 client 证书使用,所以 hosts 字段为空;
生成证书和私钥:
[root@k8s-01 ~]# cfssl gencert -ca=/etc/kubernetes/ssl/ca.pem \
-ca-key=/etc/kubernetes/ssl/ca-key.pem \
-config=/etc/kubernetes/ssl/ca-config.json \
-profile=kubernetes kube-proxy-csr.json | cfssljson -bare kube-proxy
7.5.2 创建和分发 kubeconfig 文件
[root@k8s-01 ~]# kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/ssl/ca.pem \
--embed-certs=true \
--server=${KUBE_APISERVER} \
--kubeconfig=kube-proxy.kubeconfig
[root@k8s-01 ~]# kubectl config set-credentials kube-proxy \
--client-certificate=kube-proxy.pem \
--client-key=kube-proxy-key.pem \
--embed-certs=true \
--kubeconfig=kube-proxy.kubeconfig
[root@k8s-01 ~]# kubectl config set-context default \
--cluster=kubernetes \
--user=kube-proxy \
--kubeconfig=kube-proxy.kubeconfig
[root@k8s-01 ~]# kubectl config use-context default --kubeconfig=kube-proxy.kubeconfig
分发 kubeconfig 文件:
[root@k8s-01 ~]# for node_name in ${NODE_NAMES[@]}
do
echo ">>> ${node_name}"
scp kube-proxy.kubeconfig root@${node_name}:/etc/kubernetes/conf/
done
7.5.3 创建 kube-proxy 配置文件
从 v1.10 开始,kube-proxy 部分参数可以配置文件中配置。可以使用 --write-config-to
选项生成该配置文件,或者参考 源代码的注释。
创建 kube-proxy config 文件模板:
[root@k8s-01 ~]# cat > kube-proxy-config.yaml.template <<EOF
kind: KubeProxyConfiguration
apiVersion: kubeproxy.config.k8s.io/v1alpha1
clientConnection:
burst: 200
kubeconfig: "/etc/kubernetes/conf/kube-proxy.kubeconfig"
qps: 100
bindAddress: ##NODE_IP##
healthzBindAddress: ##NODE_IP##:10256
metricsBindAddress: ##NODE_IP##:10249
enableProfiling: true
clusterCIDR: ${CLUSTER_CIDR}
hostnameOverride: ##NODE_NAME##
mode: "ipvs"
portRange: ""
iptables:
masqueradeAll: false
ipvs:
scheduler: rr
excludeCIDRs: []
EOF
bindAddress
: 监听地址;clientConnection.kubeconfig
: 连接 apiserver 的 kubeconfig 文件;clusterCIDR
: kube-proxy 根据--cluster-cidr
判断集群内部和外部流量,指定--cluster-cidr
或--masquerade-all
选项后 kube-proxy 才会对访问 Service IP 的请求做 SNAT;hostnameOverride
: 参数值必须与 kubelet 的值一致,否则 kube-proxy 启动后会找不到该 Node,从而不会创建任何 ipvs 规则;mode
: 使用 ipvs 模式;
为各节点创建和分发 kube-proxy 配置文件:
[root@k8s-01 ~]# for (( i=0; i < 3; i++ ))
do
echo ">>> ${NODE_NAMES[i]}"
sed -e "s/##NODE_NAME##/${NODE_NAMES[i]}/" -e "s/##NODE_IP##/${NODE_IPS[i]}/" kube-proxy-config.yaml.template > kube-proxy-config-${NODE_NAMES[i]}.yaml.template
scp kube-proxy-config-${NODE_NAMES[i]}.yaml.template root@${NODE_NAMES[i]}:/etc/kubernetes/work/kube-proxy-config.yaml
done
7.5.4 创建和分发 kube-proxy systemd unit 文件
[root@k8s-01 ~]# cat > kube-proxy.service <<EOF
[Unit]
Description=Kubernetes Kube-Proxy Server
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
After=network.target
[Service]
WorkingDirectory=${K8S_DIR}/kube-proxy
ExecStart=/usr/k8s/bin/kube-proxy \\
--config=/etc/kubernetes/work/kube-proxy-config.yaml \\
--logtostderr=true \\
--v=2
Restart=on-failure
RestartSec=5
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
分发 kube-proxy systemd unit 文件:
[root@k8s-01 ~]# for node_name in ${NODE_NAMES[@]}
do
echo ">>> ${node_name}"
scp kube-proxy.service root@${node_name}:/etc/systemd/system/
done
7.5.5 启动 kube-proxy 服务
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "mkdir -p ${K8S_DIR}/kube-proxy"
ssh root@${node_ip} "modprobe ip_vs_rr"
ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-proxy && systemctl restart kube-proxy"
done
7.5.6 检查启动结果
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "systemctl status kube-proxy|grep Active"
done
确保状态为 active (running),否则查看日志,确认原因:
journalctl -u kube-proxy
7.5.7 查看监听端口
[root@k8s-01 ~]# netstat -lnpt|grep kube-proxy
tcp 0 0 192.168.200.11:10249 0.0.0.0:* LISTEN 19909/kube-proxy
tcp 0 0 192.168.200.11:10256 0.0.0.0:* LISTEN 19909/kube-proxy
- 10249:http prometheus metrics port;
- 10256:http healthz port;
7.5.8 查看 ipvs 路由规则
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh root@${node_ip} "/usr/sbin/ipvsadm -ln"
done
预期输出:
>>> 192.168.200.11
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP 10.254.0.1:443 rr
-> 192.168.200.11:6443 Masq 1 0 0
-> 192.168.200.12:6443 Masq 1 0 0
-> 192.168.200.13:6443 Masq 1 0 0
>>> 192.168.200.12
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP 10.254.0.1:443 rr
-> 192.168.200.11:6443 Masq 1 0 0
-> 192.168.200.12:6443 Masq 1 0 0
-> 192.168.200.13:6443 Masq 1 0 0
>>> 192.168.200.13
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP 10.254.0.1:443 rr
-> 192.168.200.11:6443 Masq 1 0 0
-> 192.168.200.12:6443 Masq 1 0 0
-> 192.168.200.13:6443 Masq 1 0 0
可见所有通过 https 访问 K8S SVC kubernetes 的请求都转发到 kube-apiserver 节点的 6443 端口;
7.6 部署 calico 网络
kubernetes 要求集群内各节点(包括 master 节点)能通过 Pod 网段互联互通。
calico 使用 IPIP 或 BGP 技术(默认为 IPIP)为各节点创建一个可以互通的 Pod 网络。
7.6.1 安装 calico 网络插件
[root@k8s-01 ~]# curl https://docs.projectcalico.org/v3.12/manifests/calico.yaml -O
修改配置:
[root@k8s-01 ~]# cp calico.yaml calico.yaml.orig
[root@k8s-01 ~]# diff calico.yaml.orig calico.yaml
630c630,632
< value: "192.168.0.0/16"
---
> value: "172.30.0.0/16"
> - name: IP_AUTODETECTION_METHOD
> value: "interface=ens.*"
699c701
< path: /opt/cni/bin
---
> path: /usr/k8s/bin
- 将 Pod 网段地址修改为
172.30.0.0/16
;- calico 自动探查互联网卡,如果有多快网卡,则可以配置用于互联的网络接口命名正则表达式,如上面的 ens.*(根据自己服务器的网络接口名修改);
运行 calico 插件:
[root@k8s-01 ~]# mv calico.yaml /etc/kubernetes/work/
[root@k8s-01 ~]# kubectl apply -f /etc/kubernetes/work/calico.yaml
- calico 插架以 daemonset 方式运行在所有的 K8S 节点上。
7.6.2 查看 calico 运行状态
[root@k8s-01 ~]# kubectl get pods -n kube-system -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
calico-kube-controllers-59b699859f-rbllz 1/1 Running 0 108s 172.30.61.194 k8s-01 <none> <none>
calico-node-2mxnb 1/1 Running 0 108s 192.168.200.11 k8s-01 <none> <none>
calico-node-6bnm8 1/1 Running 0 108s 192.168.200.13 k8s-03 <none> <none>
calico-node-jdsxq 1/1 Running 0 108s 192.168.200.12 k8s-02 <none> <none>
使用 crictl 命令查看 calico 使用的镜像:
[root@k8s-01 ~]# crictl images | grep calico
docker.io/calico/cni v3.12.3 a6b30a97efd99 114MB
docker.io/calico/kube-controllers v3.12.3 77efab4f775c2 23.1MB
docker.io/calico/node v3.12.3 442f085df7b75 89.7MB
docker.io/calico/pod2daemon-flexvol v3.12.3 bfa72d71ec583 9.37MB
- 如果 crictl 输出为空或执行失败,则有可能是缺少配置文件
/etc/crictl.yaml
导致的,该文件的配置如下:
[root@k8s-01 ~]# cat /etc/crictl.yaml
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 10
debug: false
8、验证集群功能
本文档验证 K8S 集群是否工作正常。
8.1 检查节点状态
[root@k8s-01 ~]# kubectl get nodes
NAME STATUS ROLES AGE VERSION
k8s-01 Ready <none> 39m v1.16.6
k8s-02 Ready <none> 38m v1.16.6
k8s-03 Ready <none> 38m v1.16.6
都为 Ready 且版本为 v1.16.6 时正常。
8.2 创建测试文件
[root@k8s-01 ~]# cat > nginx-ds.yml <<EOF
apiVersion: v1
kind: Service
metadata:
name: nginx-ds
labels:
app: nginx-ds
spec:
type: NodePort
selector:
app: nginx-ds
ports:
- name: http
port: 80
targetPort: 80
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: nginx-ds
labels:
addonmanager.kubernetes.io/mode: Reconcile
spec:
selector:
matchLabels:
app: nginx-ds
template:
metadata:
labels:
app: nginx-ds
spec:
containers:
- name: my-nginx
image: nginx:1.7.9
ports:
- containerPort: 80
EOF
8.3 执行测试
[root@k8s-01 ~]# mv nginx-ds.yml /etc/kubernetes/work/
[root@k8s-01 ~]# kubectl create -f /etc/kubernetes/work/nginx-ds.yml
8.4 检查各节点的 Pod IP 连通性
[root@k8s-01 ~]# kubectl get pods -o wide -l app=nginx-ds
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
nginx-ds-66ld8 1/1 Running 0 32s 172.30.179.1 k8s-02 <none> <none>
nginx-ds-8d69f 1/1 Running 0 32s 172.30.61.195 k8s-01 <none> <none>
nginx-ds-kgc29 1/1 Running 0 32s 172.30.165.193 k8s-03 <none> <none>
在所有 Node 上分别 ping 上面三个 Pod IP,看是否连通:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh ${node_ip} "ping -c 1 172.30.179.1"
ssh ${node_ip} "ping -c 1 172.30.61.195"
ssh ${node_ip} "ping -c 1 172.30.165.193"
done
8.5 检查服务 IP 和端口可达性
[root@k8s-01 ~]# kubectl get svc -l app=nginx-ds
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
nginx-ds NodePort 10.254.48.59 <none> 80:30405/TCP 2m6s
可见:
- Service Cluster IP:10.254.48.59
- 服务端口:80
- NodePort 端口:30405
在所有 Node 上 curl Service IP:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh ${node_ip} "curl -s 10.254.48.59"
done
预期输出 nginx 欢迎页面内容。
检查服务的 NodePort 可达性
8.6 在所有 Node 上执行:
[root@k8s-01 ~]# for node_ip in ${NODE_IPS[@]}
do
echo ">>> ${node_ip}"
ssh ${node_ip} "curl -s ${node_ip}:30405"
done
预期输出 nginx 欢迎页面内容。
9、部署集群插件
插件是集群的附件组件,丰富和完善了集群的功能。
9.1 部署 coredns 插件
9.1.1 下载和配置 coredns
[root@k8s-01 ~]# git clone https://github.com/coredns/deployment.git
[root@k8s-01 ~]# mv deployment /etc/kubernetes/coredns-deployment
9.1.2 创建 coredns
[root@k8s-01 ~]# cd /etc/kubernetes/coredns-deployment/kubernetes/
[root@k8s-01 kubernetes]# ./deploy.sh -i ${CLUSTER_DNS_SVC_IP} -d ${CLUSTER_DNS_DOMAIN} | kubectl apply -f -
9.1.3 检查 coredns 功能
[root@k8s-01 kubernetes]# kubectl get all -n kube-system -l k8s-app=kube-dns
NAME READY STATUS RESTARTS AGE
pod/coredns-884d89c57-sjcz7 1/1 Running 0 15s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kube-dns ClusterIP 10.254.0.2 <none> 53/UDP,53/TCP,9153/TCP 15s
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/coredns 1/1 1 1 15s
NAME DESIRED CURRENT READY AGE
replicaset.apps/coredns-884d89c57 1 1 1 15s
9.1.4 新建一个 Deployment:
[root@k8s-01 ~]# cat > my-nginx.yaml <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
spec:
replicas: 2
selector:
matchLabels:
run: my-nginx
template:
metadata:
labels:
run: my-nginx
spec:
containers:
- name: my-nginx
image: nginx:1.7.9
ports:
- containerPort: 80
EOF
[root@k8s-01 ~]# mv my-nginx.yaml /etc/kubernetes/work/
[root@k8s-01 ~]# kubectl create -f /etc/kubernetes/work/my-nginx.yaml
9.1.5 expose 该 Deployment, 生成 my-nginx
服务:
[root@k8s-01 ~]# kubectl expose deploy my-nginx
service/my-nginx exposed
[root@k8s-01 ~]# kubectl get services my-nginx -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
my-nginx ClusterIP 10.254.105.72 <none> 80/TCP 11s run=my-nginx
创建另一个 Pod,查看 /etc/resolv.conf
是否包含 kubelet 配置的 --cluster-dns
和 --cluster-domain
,是否能够将服务 my-nginx
解析到上面显示的 Cluster IP 10.254.40.167
[root@k8s-01 ~]# cat > dnsutils-ds.yml <<EOF
apiVersion: v1
kind: Service
metadata:
name: dnsutils-ds
labels:
app: dnsutils-ds
spec:
type: NodePort
selector:
app: dnsutils-ds
ports:
- name: http
port: 80
targetPort: 80
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: dnsutils-ds
labels:
addonmanager.kubernetes.io/mode: Reconcile
spec:
selector:
matchLabels:
app: dnsutils-ds
template:
metadata:
labels:
app: dnsutils-ds
spec:
containers:
- name: my-dnsutils
image: tutum/dnsutils:latest
command:
- sleep
- "3600"
ports:
- containerPort: 80
EOF
[root@k8s-01 ~]# mv dnsutils-ds.yml /etc/kubernetes/work/
[root@k8s-01 ~]# kubectl create -f /etc/kubernetes/work/dnsutils-ds.yml
[root@k8s-01 ~]# kubectl get pods -lapp=dnsutils-ds -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
dnsutils-ds-lk9x6 1/1 Running 0 34s 172.30.165.196 k8s-03 <none> <none>
dnsutils-ds-pjrts 1/1 Running 0 34s 172.30.179.3 k8s-02 <none> <none>
dnsutils-ds-z4lv4 1/1 Running 0 34s 172.30.61.196 k8s-01 <none> <none>
[root@k8s-01 ~]# kubectl -it exec dnsutils-ds-lk9x6 cat /etc/resolv.conf
search default.svc.cluster.local. svc.cluster.local. cluster.local. localdomain
nameserver 10.254.0.2
options ndots:5
[root@k8s-01 ~]# kubectl -it exec dnsutils-ds-lk9x6 nslookup kubernetes
Server: 10.254.0.2
Address: 10.254.0.2#53
Name: kubernetes.default.svc.cluster.local
Address: 10.254.0.1
[root@k8s-01 ~]# kubectl -it exec dnsutils-ds-lk9x6 nslookup www.baidu.com
Server: 10.254.0.2
Address: 10.254.0.2#53
Non-authoritative answer:
www.baidu.com canonical name = www.a.shifen.com.
Name: www.a.shifen.com
Address: 182.61.200.7
Name: www.a.shifen.com
Address: 182.61.200.6
[root@k8s-01 ~]# kubectl -it exec dnsutils-ds-lk9x6 nslookup my-nginx
Server: 10.254.0.2
Address: 10.254.0.2#53
Name: my-nginx.default.svc.cluster.local
Address: 10.254.105.72
参考:
- https://community.infoblox.com/t5/Community-Blog/CoreDNS-for-Kubernetes-Service-Discovery/ba-p/8187
- https://coredns.io/2017/03/01/coredns-for-kubernetes-service-discovery-take-2/
- https://www.cnblogs.com/boshen-hzb/p/7511432.html
- https://github.com/kubernetes/kubernetes/tree/master/cluster/addons/dns
9.2 部署 dashboard 插件
9.2.1 下载和修改配置文件
[root@k8s-01 ~]# wget https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-rc4/aio/deploy/recommended.yaml
[root@k8s-01 ~]# mv recommended.yaml /etc/kubernetes/work/dashboard-recommended.yaml
9.2.2 执行所有定义文件
[root@k8s-01 ~]# kubectl apply -f /etc/kubernetes/work/dashboard-recommended.yaml
9.2.3 查看运行状态
[root@k8s-01 ~]# kubectl get pods -n kubernetes-dashboard
NAME READY STATUS RESTARTS AGE
dashboard-metrics-scraper-7b8b58dc8b-5ct6j 1/1 Running 0 14s
kubernetes-dashboard-6cfc8c4c9-v4wjs 1/1 Running 0 14s
9.2.4 访问 dashboard
从 1.7 开始,dashboard 只允许通过 https 访问,如果使用 kube proxy 则必须监听 localhost 或 127.0.0.1。对于 NodePort 没有这个限制,但是仅建议在开发环境中使用。对于不满足这些条件的登录访问,在登录成功后浏览器不跳转,始终停在登录界面。
通过 port forward 访问 dashboard
启动端口转发:
[root@k8s-01 work] kubectl port-forward -n kubernetes-dashboard svc/kubernetes-dashboard 4443:443 --address 0.0.0.0
浏览器访问 URL:https://192.168.200.11:4443
9.2.5 创建登录 Dashboard 的 token 和 kubeconfig 配置文件
dashboard 默认只支持 token 认证(不支持 client 证书认证),所以如果使用 Kubeconfig 文件,需要将 token 写入到该文件。
9.2.6 创建登录 token
[root@k8s-01 ~]# kubectl create sa dashboard-admin -n kube-system
serviceaccount/dashboard-admin created
[root@k8s-01 ~]# kubectl create clusterrolebinding dashboard-admin --clusterrole=cluster-admin --serviceaccount=kube-system:dashboard-admin
clusterrolebinding.rbac.authorization.k8s.io/dashboard-admin created
[root@k8s-01 ~]# ADMIN_SECRET=$(kubectl get secrets -n kube-system | grep dashboard-admin | awk '{print $1}')
[root@k8s-01 ~]# DASHBOARD_LOGIN_TOKEN=$(kubectl describe secret -n kube-system ${ADMIN_SECRET} | grep -E '^token' | awk '{print $2}')
[root@k8s-01 ~]# echo ${DASHBOARD_LOGIN_TOKEN}
eyJhbGciOiJSUzI1NiIsImtpZCI6Im1tY0N4R0h6LXZqS0FXWlVOb0c3NWo5UEoxNXd5M0hKWmZHUFNFbl9MWjAifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4taDhodGgiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiYzQwYjNjZjEtY2Y0MS00MGZkLWIyYWItNTE3NDRmMjE3MjM4Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.ocXptyk8HWyFJyGN5f0k8JlG6Y9Oc0HPMYVwy4LQXW8x-76iznp8FqgcMeTbnbsbWVIip3OUFuuQHTzHop9lDEIbm2U1ZfS3peeeqDt2R50wGDXYPds-dErMmswoiDsFaNDg_3GmzHNeaA51xrsW36UfdYbRC_dDNNFM8-X38cW9wp8JjP1wr2VsbhsVrPBG_JAssMcZl5fYw2_gr3oPkGysv-xpH6vV26l3YPaTK1pDe4YnK929WyqxwPv57twXzDAhkrDCFEvxyJIJXf9FaUANwU61k6UqnhwkixJgv0gTcsuhWUGIP-BMcMGaptHzQbvfVg3OkuE71rfY3Td6rQ
使用输出的 token 登录 Dashboard。
9.2.7 创建使用 token 的 KubeConfig 文件
# 设置集群参数
[root@k8s-01 ~]# kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/ssl/ca.pem \
--embed-certs=true \
--server=${KUBE_APISERVER} \
--kubeconfig=dashboard.kubeconfig
# 设置客户端认证参数,使用上面创建的 Token
[root@k8s-01 ~]# kubectl config set-credentials dashboard_user \
--token=${DASHBOARD_LOGIN_TOKEN} \
--kubeconfig=dashboard.kubeconfig
# 设置上下文参数
[root@k8s-01 ~]# kubectl config set-context default \
--cluster=kubernetes \
--user=dashboard_user \
--kubeconfig=dashboard.kubeconfig
# 设置默认上下文
[root@k8s-01 ~]# kubectl config use-context default --kubeconfig=dashboard.kubeconfig
用生成的 dashboard.kubeconfig 登录 Dashboard。
参考:
- https://github.com/kubernetes/dashboard/wiki/Access-control
- kubernetes/dashboard#2558
- https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/
- https://github.com/kubernetes/dashboard/wiki/Accessing-Dashboard---1.7.X-and-above
- kubernetes/dashboard#2540
9.3 部署 kube-prometheus 插架
kube-prometheus 是一整套监控解决方案,它使用 Prometheus 采集集群指标,Grafana 做展示,包含如下组件:
- The Prometheus Operator
- Highly available Prometheus
- Highly available Alertmanager
- Prometheus node-exporter
- Prometheus Adapter for Kubernetes Metrics APIs (k8s-prometheus-adapter)
- kube-state-metrics
- Grafana
其中 k8s-prometheus-adapter 使用 Prometheus 实现了 metrics.k8s.io 和 custom.metrics.k8s.io API,所以不需要再部署 metrics-server
。 如果要单独部署 metrics-server
,请参考:C.metrics-server插件.md
9.3.1 下载和安装
[root@k8s-01 ~]# git clone -b release-0.4 https://github.com/prometheus-operator/kube-prometheus.git
[root@k8s-01 ~]# mv kube-prometheus /etc/kubernetes/
# 使用中科大的 Registry
[root@k8s-01 ~]# sed -i -e 's_quay.io_quay.mirrors.ustc.edu.cn_' /etc/kubernetes/kube-prometheus/manifests/*.yaml /etc/kubernetes/kube-prometheus/manifests/setup/*.yaml
# 安装 prometheus-operator
[root@k8s-01 ~]# kubectl apply -f /etc/kubernetes/kube-prometheus/manifests/setup
# 安装 promethes metric adapter
[root@k8s-01 ~]# kubectl apply -f /etc/kubernetes/kube-prometheus/manifests/
9.3.2 查看运行状态
[root@k8s-01 ~]# kubectl get pods -n monitoring
NAME READY STATUS RESTARTS AGE
alertmanager-main-0 2/2 Running 0 2m40s
alertmanager-main-1 2/2 Running 0 2m40s
alertmanager-main-2 2/2 Running 0 2m40s
grafana-58dc7468d7-7bjcc 1/1 Running 0 2m39s
kube-state-metrics-9f8d74b69-9fx2f 3/3 Running 0 2m40s
node-exporter-gv442 2/2 Running 0 2m39s
node-exporter-nxr5b 2/2 Running 0 2m38s
node-exporter-xrzq7 2/2 Running 0 2m38s
prometheus-adapter-857f4dfcd4-4zpx8 1/1 Running 0 2m37s
prometheus-k8s-0 2/3 Running 4 2m36s
prometheus-k8s-1 3/3 Running 1 2m36s
prometheus-operator-67c94fbc6c-clx54 1/1 Running 0 3m1s
[root@k8s-01 ~]# kubectl top pods -n monitoring
NAME CPU(cores) MEMORY(bytes)
alertmanager-main-0 0m 15Mi
alertmanager-main-1 0m 16Mi
alertmanager-main-2 0m 17Mi
grafana-58dc7468d7-7bjcc 0m 34Mi
kube-state-metrics-9f8d74b69-9fx2f 1m 35Mi
node-exporter-gv442 0m 20Mi
node-exporter-nxr5b 1m 13Mi
node-exporter-xrzq7 0m 22Mi
prometheus-adapter-857f4dfcd4-4zpx8 0m 14Mi
prometheus-k8s-0 0m 122Mi
prometheus-k8s-1 13m 203Mi
prometheus-operator-67c94fbc6c-clx54 0m 18Mi
9.3.3 访问 Prometheus UI
启动服务代理:
[root@k8s-01 ~]# kubectl port-forward --address 0.0.0.0 pod/prometheus-k8s-0 -n monitoring 9090:9090
Forwarding from 0.0.0.0:9090 -> 9090
- port-forward 依赖 socat。
浏览器访问:http://192.168.200.11:9090/graph?g0.range_input=15m&g0.expr=instance%3Anode_cpu_utilisation%3Arate1m&g0.tab=0
9.3.4 访问 Grafana UI
启动代理:
[root@k8s-01 ~]# kubectl port-forward --address 0.0.0.0 svc/grafana -n monitoring 3000:3000
Forwarding from 0.0.0.0:3000 -> 3000
浏览器访问:http://192.168.200.11:3000/
用 admin/admin 登录:
然后,就可以看到各种预定义的 dashboard 了:
9.4 部署 EFK 插件
注意:
- kuberntes 自带插件的 manifests yaml 文件使用 gcr.io 的 docker registry,国内被墙,需要手动替换为其它 registry 地址;
- 可以从微软中国提供的 gcr.io 免费代理下载被墙的镜像;
9.4.1 修改配置文件
将下载的 kubernetes-server-linux-amd64.tar.gz 解压后,再解压其中的 kubernetes-src.tar.gz 文件。
[root@k8s-01 ~]# wget https://dl.k8s.io/v1.16.6/kubernetes-server-linux-amd64.tar.gz
[root@k8s-01 ~]# tar xf kubernetes-server-linux-amd64.tar.gz
[root@k8s-01 ~]# cd kubernetes
[root@k8s-01 kubernetes]# tar xf kubernetes-src.tar.gz
EFK 目录是 /cluster/addons/fluentd-elasticsearch
。
[root@k8s-01 kubernetes]# mv cluster /etc/kubernetes/
# 使用中科大的 Registry
[root@k8s-01 ~]# sed -i -e 's_quay.io_quay.mirrors.ustc.edu.cn_' /etc/kubernetes/cluster/addons/fluentd-elasticsearch/es-statefulset.yaml
[root@k8s-01 ~]# sed -i -e 's_quay.io_quay.mirrors.ustc.edu.cn_' /etc/kubernetes/cluster/addons/fluentd-elasticsearch/fluentd-es-ds.yaml
9.4.2 执行定义文件
[root@k8s-01 ~]# kubectl apply -f /etc/kubernetes/cluster/addons/fluentd-elasticsearch
9.4.3 检查执行结果
[root@k8s-01 ~]# kubectl get all -n kube-system |grep -E 'elasticsearch|fluentd|kibana'
pod/elasticsearch-logging-0 1/1 Running 0 4m1s
pod/elasticsearch-logging-1 1/1 Running 0 2m33s
pod/fluentd-es-v2.7.0-8qmng 1/1 Running 0 4m2s
pod/fluentd-es-v2.7.0-dfgcz 1/1 Running 0 4m2s
pod/fluentd-es-v2.7.0-xsmwh 1/1 Running 0 4m2s
pod/kibana-logging-75888755d6-rjltk 1/1 Running 2 4m2s
service/elasticsearch-logging ClusterIP 10.254.96.176 <none> 9200/TCP 4m3s
service/kibana-logging ClusterIP 10.254.148.183 <none> 5601/TCP 4m2s
daemonset.apps/fluentd-es-v2.7.0 3 3 3 3 3 <none> 4m2s
deployment.apps/kibana-logging 1/1 1 1 4m2s
replicaset.apps/kibana-logging-75888755d6 1 1 1 4m2s
statefulset.apps/elasticsearch-logging 2/2 4m2s
kibana Pod 第一次启动时会用较长时间(0-20分钟)来优化和 Cache 状态页面,可以 tailf 该 Pod 的日志观察进度:
[root@k8s-01 ~]# kubectl logs kibana-logging-75888755d6-rjltk -n kube-system -f
注意:只有当 Kibana pod 启动完成后,浏览器才能查看 kibana dashboard,否则会被拒绝。
9.4.4 通过 kubectl proxy 访问 kibana
创建代理:
[root@k8s-01 ~]# kubectl proxy --address='192.168.200.11' --port=8086 --accept-hosts='^*$'
Starting to serve on 192.168.200.11:8086
浏览器访问 URL:http://192.168.200.11:8086/api/v1/namespaces/kube-system/services/kibana-logging/proxy
在 Management -> Indices 页面创建一个 index(相当于 mysql 中的一个 database),选中 Index contains time-based events
,使用默认的 logstash-*
pattern,点击 Create
;文章来源:https://www.toymoban.com/news/detail-431241.html
创建 Index 后,稍等几分钟就可以在 Discover
菜单下看到 ElasticSearch logging 中汇聚的日志;文章来源地址https://www.toymoban.com/news/detail-431241.html
到了这里,关于手动搭建高可用的 kubernetes 集群(v1.16.6)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!