架构解析
高可用架构图
组件用途
- Etcd Cluster
- ectd是一个键值数据库,主要存放Kubernetes数据,如创建的资源、变更的操作等;
- Master
- Kubernetes中的控制节点,主要用于控制Kubernetes集群;
- Node
- Kubernetes中的工作节点,主要用于运行Kubernetes集群部署的Pod;
- Kube-APIServer
- Kubernetes中的控制组件,Kubernetes集群中所有流量都会经过Kube-APIServer;
- ControllerManager
- Kubernetes中的控制组件,主要用于监控Kubernetes集群的状态;
- Scheduler
- Kubernetes中的调度组件,主要用于控制Kubernetes集群中的Pod调度到哪个Node节点去运行;
- Load Balancer
- Kubernetes中各个节点直接负载均衡器,一般使用keepailved和haproxy组合实现负责均衡;
- Kubelet
- Kubernetes中的代理组件,主要用于保证Kubernetes集群中的Pod运行状态;
- Kube-Proxy
- Kubernetes中的网络代理组件,主要用于保证Kubernetes集群中的Pod访问控制;
部署集群
主机规划
主机规划
主机名称 | 主机地址 | 主机资源 | 安装组件 | 主机用途 |
---|---|---|---|---|
k8s-master-01 | 192.168.23.101 | 2C4G;200G | haproxy+keepalived+ectd+Kubernetes-Master | 集群管理节点 |
k8s-master-02 | 192.168.23.102 | 2C4G;200G | haproxy+keepalived+ectd+Kubernetes-Master | 集群管理节点 |
k8s-master-03 | 192.168.23.103 | 2C4G;200G | haproxy+keepalived+ectd+Kubernetes-Master | 集群管理节点 |
k8s-node-04 | 192.168.23.104 | 1C2G;200G | Kubernetes-Node | 集群工作节点 |
k8s-node-05 | 192.168.23.105 | 1C2G;200G | Kubernetes-Node | 集群工作节点 |
Vip | 192.168.23.100 | 集群虚拟IP | ||
K8S Service | k8s service网段为192.168.0.0/16 | |||
K8S Pod | k8s Pod网段为172.16.0.0/12 | |||
注意事项
(1)宿主机网段、K8s Service网段、Pod网段不能重复
(2)主机信息,服务器IP地址不能设置成dhcp,要配置成静态IP
(3)VIP(虚拟IP)不要和公司内网IP重复,首先去ping一下,不通才可用。VIP需要和你的主机在同一个局域网内!不是直接用我的VIP!!!
(4)公有云的话,VIP为公有云的负载均衡的IP,比如阿里云的SLB地址,腾讯云的ELB地址,注意公有云的负载均衡都是内网的负载均衡。
(5)生产环境中etcd一定要和系统盘分开,一定要用ssd硬盘。
(6)Docker数据盘也要和系统盘分开,有条件的话可以使用ssd硬盘。
基础安装
注意:涉及所有节点
国内安装源
- 阿里云yum源
cat > /etc/yum.repos.d/CentOS-7-ali.repo << 'EOF'
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client. You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#
[base]
name=CentOS-$releasever - Base - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/os/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/os/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#released updates
[updates]
name=CentOS-$releasever - Updates - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/updates/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/updates/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/extras/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/extras/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#additional packages that extend functionality of existing packages
EOF
- 阿里云epel源
cat > epel-7-ali.repo << 'EOF'
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://mirrors.aliyun.com/epel/7/$basearch
failovermethod=priority
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
baseurl=http://mirrors.aliyun.com/epel/7/$basearch/debug
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=0
[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
baseurl=http://mirrors.aliyun.com/epel/7/SRPMS
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=0
EOF
地址解析
- 修改hostname
hostnamectl set-hostname k8s-master-01
hostnamectl set-hostname k8s-master-02
hostnamectl set-hostname k8s-master-03
hostnamectl set-hostname k8s-node-01
hostnamectl set-hostname k8s-node-02
- 配置hosts
cat >> /etc/hosts << EOF
192.168.23.100 k8s-lb
192.168.23.101 k8s-master-01
192.168.23.102 k8s-master-02
192.168.23.103 k8s-master-03
192.168.23.104 k8s-node-01
192.168.23.105 k8s-node-02
EOF
免密登录
- 创建秘钥(k8s-master-01节点)
ssh-keygen
# Generating public/private rsa key pair.
# Enter file in which to save the key (/root/.ssh/id_rsa):
# Created directory '/root/.ssh'.
# Enter passphrase (empty for no passphrase):
# Enter same passphrase again:
# Your identification has been saved in /root/.ssh/id_rsa.
# Your public key has been saved in /root/.ssh/id_rsa.pub.
# The key fingerprint is:
# SHA256:ocKDZzHfVRKKLCZ1R8d5ZJ597AWobrc3e/m4iYsn1lI root@k8s-master-01
# The key's randomart image is:
# +---[RSA 2048]----+
# | . ..o.+++.. |
# | . o o oo=oo o |
# | . = o o .oo . +|
# | = = o o. o.|
# | . * o S. .|
# | o o o E |
# | . + . .|
# | +.+.o+.|
# | ..+oo==o|
# +----[SHA256]-----+
- 分发秘钥
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh-copy-id -i root@$IP_HOST
echo "------$IP_HOST OK------"
done
必备工具
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "yum -y install wget jq psmisc vim net-tools telnet yum-utils device-mapper-persistent-data lvm2 git vim"
echo "------$IP_HOST OK------"
done
内核升级
- 下载内核
cd /root
wget http://193.49.22.109/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-devel-4.19.12-1.el7.elrepo.x86_64.rpm
wget http://193.49.22.109/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-4.19.12-1.el7.elrepo.x86_64.rpm
- 安装升级
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
scp /root/kernel-ml* root@$IP_HOST:/root/
ssh root@$IP_HOST "yum -y install /root/kernel-ml*"
echo "------$IP_HOST OK------"
done
- 升级内核
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "grub2-set-default 0 && grub2-mkconfig -o /boot/grub2/grub.cfg"
echo "------$IP_HOST OK------"
done
#统一重启
- 检查内核
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "uname -r"
echo "------$IP_HOST OK------"
done
时钟同步
- 安装工具
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "yum -y install ntpdate chrony"
ssh root@$IP_HOST "sed -ri 's/^server/#server/g' /etc/chrony.conf && echo 'server ntp.aliyun.com iburst' >> /etc/chrony.conf"
ssh root@$IP_HOST "systemctl enable --now chronyd"
echo "------$IP_HOST OK------"
done
- 定时任务
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "echo '*/10 * * * * /usr/sbin/ntpdate ntp.aliyun.com' >> /var/spool/cron/root"
echo "------$IP_HOST OK------"
done
- 验证同步
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "chronyc sourcestats -v"
echo "------$IP_HOST OK------"
done
基础环境
注意:涉及所有节点
关闭selinux
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "setenforce 0 && sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/sysconfig/selinux"
echo "------$IP_HOST OK------"
done
关闭firewalld
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl stop firewalld && systemctl disable firewalld"
echo "------$IP_HOST OK------"
done
关闭swap
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "swapoff -a && sysctl -w vm.swappiness=0 && sed -ri '/^[^#]*swap/s@^@#@' /etc/fstab"
echo "------$IP_HOST OK------"
done
关闭dnsmasq
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl stop dnsmasq && systemctl disable dnsmasq"
echo "------$IP_HOST OK------"
done
集群调优
注意:涉及所有节点
配置系统资源限制
cat >> /root/limits.conf << EOF
* soft noproc 655350
* hard noproc 655350
* soft nofile 655350
* hard nofile 655350
EOF
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
scp /root/limits.conf root@$IP_HOST:/etc/security/
echo "------$IP_HOST OK------"
done
#用于调整用户的系统资源限制,要求大于65535
配置系统调优参数
开启一些k8s集群中必须的内核参数,所有节点配置k8s内核
cat > /root/k8s.conf << EOF
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-iptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
fs.may_detach_mounts = 1
vm.overcommit_memory=1
net.ipv4.conf.all.route_localnet = 1
vm.panic_on_oom=0
fs.inotify.max_user_watches=89100
fs.file-max=52706963
fs.nr_open=52706963
net.netfilter.nf_conntrack_max=2310720
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl =15
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_orphans = 327680
net.ipv4.tcp_orphan_retries = 3
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.ip_conntrack_max = 65536
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_timestamps = 0
net.core.somaxconn = 16384
EOF
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
scp /root/k8s.conf root@$IP_HOST:/etc/sysctl.d/
ssh root@$IP_HOST "sysctl --system"
echo "------$IP_HOST OK------"
done
#用于系统调优参数配置
配置文件优化参数
cat > /root/k8s.conf <<EOF
* soft nproc 1048576
* hard nproc 1048576
* soft nofile 1048576
* hard nofile 1048576
root soft nproc 1048576
root hard nproc 1048576
root soft nofile 1048576
root hard nofile 1048576
EOF
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
scp /root/k8s.conf root@$IP_HOST:/etc/security/limits.d/
echo "------$IP_HOST OK------"
done
#用于文件最大打开数调优
配置日志优化参数
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "sed -ri 's/^\$ModLoad imjournal/#&/' /etc/rsyslog.conf"
ssh root@$IP_HOST "sed -ri 's/^\$IMJournalStateFile/#&/' /etc/rsyslog.conf"
ssh root@$IP_HOST "sed -ri 's/^#(DefaultLimitCORE)=/\1=100000/' /etc/systemd/system.conf"
ssh root@$IP_HOST "sed -ri 's/^#(DefaultLimitNOFILE)=/\1=100000/' /etc/systemd/system.conf"
echo "------$IP_HOST OK------"
done
#用于优化日志处理,减少磁盘IO
配置连接优化参数
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "sed -ri 's/^#(UseDNS )yes/\1no/' /etc/ssh/sshd_config"
echo "------$IP_HOST OK------"
done
#用于ssh 连接优化
组件安装
安装ipvsadm
注意:涉及所有节点
- 安装ipvsadm组件
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "yum -y install ipvsadm ipset sysstat conntrack libseccomp"
echo "------$IP_HOST OK------"
done
- 配置ipvs模块
注意: 在内核4.19+版本nf_conntrack_ipv4已经改为nf_conntrack, 4.18以下使用nf_conntrack_ipv4即可
cat > /root/ipvs.conf << EOF
ip_vs
ip_vs_lc
ip_vs_wlc
ip_vs_rr
ip_vs_wrr
ip_vs_lblc
ip_vs_lblcr
ip_vs_dh
ip_vs_sh
ip_vs_fo
ip_vs_nq
ip_vs_sed
ip_vs_ftp
ip_vs_sh
nf_conntrack
ip_tables
ip_set
xt_set
ipt_set
ipt_rpfilter
ipt_REJECT
ipip
EOF
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "modprobe -- ip_vs && modprobe -- ip_vs_rr && modprobe -- ip_vs_wrr && modprobe -- ip_vs_sh && modprobe -- nf_conntrack"
scp /root/ipvs.conf root@$IP_HOST:/etc/modules-load.d/
echo "------$IP_HOST OK------"
done
- 启动ipvsadm并验证是否加载
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl enable --now systemd-modules-load.service && systemctl status systemd-modules-load.service"
ssh root@$IP_HOST "lsmod | grep -e ip_vs -e nf_conntrack"
echo "------$IP_HOST OK------"
done
安装Containerd
注意:涉及所有节点
- 安装Containerd
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
#解决依赖
ssh root@$IP_HOST "yum -y install yum-utils && yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo"
#安装服务
ssh root@$IP_HOST "yum -y install docker-ce-20.10.* docker-ce-cli-20.10.* containerd"
echo "------$IP_HOST OK------"
done
- 配置Containerd所需模块
cat > /root/containerd.conf << EOF
overlay
br_netfilter
EOF
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
#配置Containerd所需的模块
scp /root/containerd.conf root@$IP_HOST:/etc/modules-load.d/
#加载模块
ssh root@$IP_HOST "modprobe -- overlay && modprobe -- br_netfilter"
echo "------$IP_HOST OK------"
done
- 配置Containerd所需内核
cat > /root/99-kubernetes-cri.conf << EOF
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
#配置Containerd所需的内核
scp /root/99-kubernetes-cri.conf root@$IP_HOST:/etc/sysctl.d/
#加载内核
ssh root@$IP_HOST "sysctl --system"
echo "------$IP_HOST OK------"
done
- 配置Containerd的配置文件
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
#生成配置文件
ssh root@$IP_HOST "mkdir -p /etc/containerd && containerd config default > /etc/containerd/config.toml"
echo "------$IP_HOST OK------"
done
- 手动调整Containerd的配置文件
#vim /etc/containerd/config.toml
#找到containerd.runtimes.runc.options,添加SystemdCgroup = true(如果已存在直接修改,否则会报错)
#将sandbox_image的Pause镜像改成符合自己版本的地址registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.7
cat /etc/containerd/config.toml | grep SystemdCgroup
cat /etc/containerd/config.toml | grep sandbox_image
- 启动Containerd
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl daemon-reload && systemctl enable --now containerd && systemctl status containerd"
echo "------$IP_HOST OK------"
done
- 配置crictl客户端连接
#配置crictl客户端连接的运行时位置
cat > /root/crictl.yaml <<EOF
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 10
debug: false
EOF
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
scp /root/crictl.yaml root@$IP_HOST:/etc/
echo "------$IP_HOST OK------"
done
安装Keepalived
注意:涉及所有Master节点
- 安装Keepalived
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "yum -y install keepalived"
echo "------$IP_HOST OK------"
done
- 配置Keepalived健康检查
cat > /root/check_apiserver.sh << 'EOF'
#!/bin/bash
err=0
for k in $(seq 1 3)
do
check_code=$(pgrep haproxy)
if [[ $check_code == "" ]]; then
err=$(expr $err + 1)
sleep 1
continue
else
err=0
break
fi
done
if [[ $err != "0" ]]; then
echo "systemctl stop keepalived"
/usr/bin/systemctl stop keepalived
exit 1
else
exit 0
fi
EOF
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
scp /root/check_apiserver.sh root@$IP_HOST:/etc/keepalived/
ssh root@$IP_HOST "chmod +x /etc/keepalived/check_apiserver.sh"
echo "------$IP_HOST OK------"
done
- 配置Keepalived(Master)
所有Master节点配置KeepAlived,配置不一样。注意节点的IP和网卡以及VIP地址。
TYPE=MASTER
NETWORK_CARD=`ip addr | grep inet | grep -v $$ | grep brd | awk -F ' ' '{print $NF}'`
LOCAL_IP_HOST=`ip addr | grep inet | grep -v $$ | grep brd | awk -F ' ' '{print $2}' | awk -F '/' '{print $1}'`
LB_IP_HOST=192.168.23.100
cat > /etc/keepalived/keepalived.conf << EOF
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_apiserver {
script "/etc/keepalived/check_apiserver.sh"
interval 5
weight -5
fall 2
rise 1
}
vrrp_instance VI_1 {
state $TYPE
interface $NETWORK_CARD
mcast_src_ip $LOCAL_IP_HOST
virtual_router_id 51
priority 101
nopreempt
advert_int 2
authentication {
auth_type PASS
auth_pass K8SHA_KA_AUTH
}
virtual_ipaddress {
$LB_IP_HOST
}
track_script {
chk_apiserver
}
}
EOF
- 配置Keepalived(Backup)
TYPE=BACKUP
NETWORK_CARD=`ip addr | grep inet | grep -v $$ | grep brd | awk -F ' ' '{print $NF}'`
LOCAL_IP_HOST=`ip addr | grep inet | grep -v $$ | grep brd | awk -F ' ' '{print $2}' | awk -F '/' '{print $1}'`
LB_IP_HOST=192.168.23.100
cat > /etc/keepalived/keepalived.conf << EOF
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_apiserver {
script "/etc/keepalived/check_apiserver.sh"
interval 5
weight -5
fall 2
rise 1
}
vrrp_instance VI_1 {
state $TYPE
interface $NETWORK_CARD
mcast_src_ip $LOCAL_IP_HOST
virtual_router_id 51
priority 100
nopreempt
advert_int 2
authentication {
auth_type PASS
auth_pass K8SHA_KA_AUTH
}
virtual_ipaddress {
$LB_IP_HOST
}
track_script {
chk_apiserver
}
}
EOF
- 启动并验证Keepalived
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl enable --now keepalived && systemctl status keepalived"
echo "------$IP_HOST OK------"
done
安装HAproxy
注意:涉及所有Master节点
- 安装HAproxy
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "yum -y install haproxy"
echo "------$IP_HOST OK------"
done
- 配置HAproxy
HOSTNAME_1=k8s-master-01
HOSTNAME_2=k8s-master-02
HOSTNAME_3=k8s-master-03
IPADDR_1=192.168.23.101
IPADDR_2=192.168.23.102
IPADDR_3=192.168.23.10
cat > /root/haproxy.cfg << EOF
global
maxconn 2000
ulimit-n 16384
log 127.0.0.1 local0 err
stats timeout 30s
defaults
log global
mode http
option httplog
timeout connect 5000
timeout client 50000
timeout server 50000
timeout http-request 15s
timeout http-keep-alive 15s
frontend k8s-master
bind 0.0.0.0:8443
bind 127.0.0.1:8443
mode tcp
option tcplog
tcp-request inspect-delay 5s
default_backend k8s-master
backend k8s-master
mode tcp
option tcplog
option tcp-check
balance roundrobin
default-server inter 10s downinter 5s rise 2 fall 2 slowstart 60s maxconn 250 maxqueue 256 weight 100
server $HOSTNAME_1 $IPADDR_1:6443 check
server $HOSTNAME_2 $IPADDR_2:6443 check
server $HOSTNAME_3 $IPADDR_3:6443 check
EOF
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
scp /root/haproxy.cfg root@$IP_HOST:/etc/haproxy/
echo "------$IP_HOST OK------"
done
- 启动并验证HAproxy
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl enable --now haproxy && systemctl status haproxy"
echo "------$IP_HOST OK------"
done
安装etcd
注意:涉及所有Master节点
- 下载etcd
cd /opt/
wget https://github.com/etcd-io/etcd/releases/download/v3.5.4/etcd-v3.5.4-linux-amd64.tar.gz
- 安装etcd
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
scp /opt/etcd-v3.5.4-linux-amd64.tar.gz root@$IP_HOST:/root/
ssh root@$IP_HOST "tar -zxvf etcd-v3.5.4-linux-amd64.tar.gz --strip-components=1 -C /usr/local/bin etcd-v3.5.4-linux-amd64/etcd{,ctl}"
echo "------$IP_HOST OK------"
done
- 检查etcd
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "etcd --version"
echo "------$IP_HOST OK------"
done
安装K8S
注意:涉及所有节点
- 下载K8S
cd /opt/
wget https://dl.k8s.io/v1.24.0/kubernetes-server-linux-amd64.tar.gz
- 安装K8S
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
scp /opt/kubernetes-server-linux-amd64.tar.gz root@$IP_HOST:/root/
ssh root@$IP_HOST "tar -xf kubernetes-server-linux-amd64.tar.gz --strip-components=3 -C /usr/local/bin kubernetes/server/bin/kube{let,ctl,-apiserver,-controller-manager,-scheduler,-proxy}"
echo "------$IP_HOST OK------"
done
for IP_HOST in 192.168.23.10{4,5}; do
echo "------$IP_HOST------"
scp /opt/kubernetes-server-linux-amd64.tar.gz root@$IP_HOST:/root/
ssh root@$IP_HOST "tar -xf kubernetes-server-linux-amd64.tar.gz --strip-components=3 -C /usr/local/bin kubernetes/server/bin/kube{let,-proxy}"
echo "------$IP_HOST OK------"
done
- 检查K8S
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "kubelet --version"
echo "------$IP_HOST OK------"
done
文件目录
注意:涉及所有节点
创建CNI目录
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "mkdir -p /opt/cni/bin"
echo "------$IP_HOST OK------"
done
下载K8S文件
- 安装git工具
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "yum -y install git"
ssh root@$IP_HOST "git config --global user.name 'wangmingqu' && git config --global user.email '[email protected]' && git init"
echo "------$IP_HOST OK------"
done
- 安装文件
#参考 dotbalo 的文档,文档地址:https://github.com/dotbalo/k8s-ha-install
#git clone https://github.com/dotbalo/k8s-ha-install.git
- 下载k8s文件
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
scp /opt/k8s-ha-install.tar.gz root@$IP_HOST:/root/
ssh root@$IP_HOST "tar -zxvf /opt/k8s-ha-install.tar.gz -C /root/"
ssh root@$IP_HOST "cd /root/k8s-ha-install && git checkout manual-installation-v1.24.x"
echo "------$IP_HOST OK------"
done
生成证书
证书工具
注意:涉及k8s-master-01节点
wget "https://pkg.cfssl.org/R1.2/cfssl_linux-amd64" -O /usr/local/bin/cfssl
wget "https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64" -O /usr/local/bin/cfssljson
chmod +x /usr/local/bin/cfssl /usr/local/bin/cfssljson
生成etcd证书
- 创建证书目录
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "mkdir /etc/etcd/ssl -p"
echo "------$IP_HOST OK------"
done
- 生成证书
cd /root/k8s-ha-install/pki
# 生成etcd CA证书和CA证书的key
cfssl gencert -initca etcd-ca-csr.json | cfssljson -bare /etc/etcd/ssl/etcd-ca
# 注意主机名称和主机地址
cfssl gencert \
-ca=/etc/etcd/ssl/etcd-ca.pem \
-ca-key=/etc/etcd/ssl/etcd-ca-key.pem \
-config=ca-config.json \
-hostname=127.0.0.1,k8s-master-01,k8s-master-02,k8s-master-03,192.168.23.101,192.168.23.102,192.168.23.103 \
-profile=kubernetes \
etcd-csr.json | cfssljson -bare /etc/etcd/ssl/etcd
- 分发证书
for IP_HOST in 192.168.23.10{2..5}; do
echo "------$IP_HOST------"
scp /etc/etcd/ssl/* root@$IP_HOST:/etc/etcd/ssl/
echo "------$IP_HOST OK------"
done
生成K8S组件证书
- 创建证书目录
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "mkdir -p /etc/kubernetes/pki"
echo "------$IP_HOST OK------"
done
- 生成kubernetes证书
cd /root/k8s-ha-install/pki
cfssl gencert -initca ca-csr.json | cfssljson -bare /etc/kubernetes/pki/ca
#192.168.0.是k8s service的网段,如果说需要更改k8s service网段,那就需要更改192.168.0.1,
#如果不是高可用集群,192.168.23.100为Master01的IP
cfssl gencert \
-ca=/etc/kubernetes/pki/ca.pem \
-ca-key=/etc/kubernetes/pki/ca-key.pem \
-config=ca-config.json \
-hostname=192.168.0.1,192.168.23.100,127.0.0.1,kubernetes,kubernetes.default,kubernetes.default.svc,kubernetes.default.svc.cluster,kubernetes.default.svc.cluster.local,192.168.23.101,192.168.23.102,192.168.23.103 \
-profile=kubernetes \
apiserver-csr.json | cfssljson -bare /etc/kubernetes/pki/apiserver
- 生成apiserver的聚合证书
cd /root/k8s-ha-install/pki
cfssl gencert \
-initca front-proxy-ca-csr.json | cfssljson -bare /etc/kubernetes/pki/front-proxy-ca
cfssl gencert \
-ca=/etc/kubernetes/pki/front-proxy-ca.pem \
-ca-key=/etc/kubernetes/pki/front-proxy-ca-key.pem \
-config=ca-config.json \
-profile=kubernetes \
front-proxy-client-csr.json | cfssljson -bare /etc/kubernetes/pki/front-proxy-client
由此警告结果可以忽略
# 2024/08/25 21:12:56 [INFO] generate received request
# 2024/08/25 21:12:56 [INFO] received CSR
# 2024/08/25 21:12:56 [INFO] generating key: rsa-2048
# 2024/08/25 21:12:57 [INFO] encoded CSR
# 2024/08/25 21:12:57 [INFO] signed certificate with serial number 683767219109330454087700751007901444283358948366
# 2024/08/25 21:12:57 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
# websites. For more information see the Baseline Requirements for the Issuance and Management
# of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
# specifically, section 10.2.3 ("Information Requirements").
- 生成controller-manage的证书
cd /root/k8s-ha-install/pki
cfssl gencert \
-ca=/etc/kubernetes/pki/ca.pem \
-ca-key=/etc/kubernetes/pki/ca-key.pem \
-config=ca-config.json \
-profile=kubernetes \
manager-csr.json | cfssljson -bare /etc/kubernetes/pki/controller-manager
# 注意,如果不是高可用集群,192.168.23.100:8443改为k8s-master-01的地址,8443改为apiserver的端口,默认是6443
# set-cluster:设置一个集群项
kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.pem \
--embed-certs=true \
--server=https://192.168.23.100:8443 \
--kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
# 设置一个环境项,一个上下文
kubectl config set-context system:kube-controller-manager@kubernetes \
--cluster=kubernetes \
--user=system:kube-controller-manager \
--kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
# set-credentials 设置一个用户项
kubectl config set-credentials system:kube-controller-manager \
--client-certificate=/etc/kubernetes/pki/controller-manager.pem \
--client-key=/etc/kubernetes/pki/controller-manager-key.pem \
--embed-certs=true \
--kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
# 使用某个环境当做默认环境
kubectl config use-context system:kube-controller-manager@kubernetes \
--kubeconfig=/etc/kubernetes/controller-manager.kubeconfig
- 生成scheduler的证书
cd /root/k8s-ha-install/pki
cfssl gencert \
-ca=/etc/kubernetes/pki/ca.pem \
-ca-key=/etc/kubernetes/pki/ca-key.pem \
-config=ca-config.json \
-profile=kubernetes \
scheduler-csr.json | cfssljson -bare /etc/kubernetes/pki/scheduler
# 注意,如果不是高可用集群,192.168.23.100:8443改为k8s-master-01的地址,8443改为apiserver的端口,默认是6443
# set-cluster:设置一个集群项
kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.pem \
--embed-certs=true \
--server=https://192.168.23.100:8443 \
--kubeconfig=/etc/kubernetes/scheduler.kubeconfig
# set-credentials 设置一个用户项
kubectl config set-credentials system:kube-scheduler \
--client-certificate=/etc/kubernetes/pki/scheduler.pem \
--client-key=/etc/kubernetes/pki/scheduler-key.pem \
--embed-certs=true \
--kubeconfig=/etc/kubernetes/scheduler.kubeconfig
# 设置一个环境项,一个上下文
kubectl config set-context system:kube-scheduler@kubernetes \
--cluster=kubernetes \
--user=system:kube-scheduler \
--kubeconfig=/etc/kubernetes/scheduler.kubeconfig
# 使用某个环境当做默认环境
kubectl config use-context system:kube-scheduler@kubernetes \
--kubeconfig=/etc/kubernetes/scheduler.kubeconfig
- 生成admin的证书
cd /root/k8s-ha-install/pki
cfssl gencert \
-ca=/etc/kubernetes/pki/ca.pem \
-ca-key=/etc/kubernetes/pki/ca-key.pem \
-config=ca-config.json \
-profile=kubernetes \
admin-csr.json | cfssljson -bare /etc/kubernetes/pki/admin
# 注意,如果不是高可用集群,192.168.23.100:8443改为k8s-master-01的地址,8443改为apiserver的端口,默认是6443
# set-cluster:设置一个集群项
kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.pem \
--embed-certs=true \
--server=https://192.168.23.100:8443 \
--kubeconfig=/etc/kubernetes/admin.kubeconfig
# set-credentials 设置一个用户项
kubectl config set-credentials kubernetes-admin \
--client-certificate=/etc/kubernetes/pki/admin.pem \
--client-key=/etc/kubernetes/pki/admin-key.pem \
--embed-certs=true \
--kubeconfig=/etc/kubernetes/admin.kubeconfig
# 设置一个环境项,一个上下文
kubectl config set-context kubernetes-admin@kubernetes \
--cluster=kubernetes \
--user=kubernetes-admin \
--kubeconfig=/etc/kubernetes/admin.kubeconfig
# 使用某个环境当做默认环境
kubectl config use-context kubernetes-admin@kubernetes \
--kubeconfig=/etc/kubernetes/admin.kubeconfig
- 创建ServiceAccount Key > secret
openssl genrsa -out /etc/kubernetes/pki/sa.key 2048
openssl rsa -in /etc/kubernetes/pki/sa.key -pubout -out /etc/kubernetes/pki/sa.pub
- 分发证书-分发到Master
for IP_HOST in 192.168.23.10{2,3}; do
echo "------$IP_HOST------"
scp /etc/kubernetes/* root@$IP_HOST:/etc/kubernetes/
scp /etc/kubernetes/pki/* root@$IP_HOST:/etc/kubernetes/pki/
echo "------$IP_HOST OK------"
done
- 分发证书-分发到Node
for IP_HOST in 192.168.23.10{4,5}; do
echo "------$IP_HOST------"
scp /etc/kubernetes/pki/{ca,ca-key,front-proxy-ca}.pem root@$IP_HOST:/etc/kubernetes/pki/
echo "------$IP_HOST OK------"
done
集群配置
目录准备
注意:涉及所有节点
- 创建目录
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "mkdir -p /etc/kubernetes/manifests/ /etc/systemd/system/kubelet.service.d /var/lib/kubelet /var/log/kubernetes"
echo "------$IP_HOST OK------"
done
etcd配置
注意:涉及所有Master节点
etcd配置大致相同,注意修改每个Master节点的etcd配置的主机名和IP地址。
- k8s-master-01配置
cat > /etc/etcd/etcd.config.yml << EOF
name: 'k8s-master-01'
data-dir: /var/lib/etcd
wal-dir: /var/lib/etcd/wal
snapshot-count: 5000
heartbeat-interval: 100
election-timeout: 1000
quota-backend-bytes: 0
listen-peer-urls: 'https://192.168.23.101:2380'
listen-client-urls: 'https://192.168.23.101:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://192.168.23.101:2380'
advertise-client-urls: 'https://192.168.23.101:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'k8s-master-01=https://192.168.23.101:2380,k8s-master-02=https://192.168.23.102:2380,k8s-master-03=https://192.168.23.103:2380'
initial-cluster-token: 'etcd-k8s-cluster'
initial-cluster-state: 'new'
strict-reconfig-check: false
enable-v2: true
enable-pprof: true
proxy: 'off'
proxy-failure-wait: 5000
proxy-refresh-interval: 30000
proxy-dial-timeout: 1000
proxy-write-timeout: 5000
proxy-read-timeout: 0
client-transport-security:
cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
client-cert-auth: true
trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
auto-tls: true
peer-transport-security:
cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
peer-client-cert-auth: true
trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
auto-tls: true
debug: false
log-package-levels:
log-outputs: [default]
force-new-cluster: false
EOF
- k8s-master-02配置
cat > /etc/etcd/etcd.config.yml << EOF
name: 'k8s-master-02'
data-dir: /var/lib/etcd
wal-dir: /var/lib/etcd/wal
snapshot-count: 5000
heartbeat-interval: 100
election-timeout: 1000
quota-backend-bytes: 0
listen-peer-urls: 'https://192.168.23.102:2380'
listen-client-urls: 'https://192.168.23.102:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://192.168.23.102:2380'
advertise-client-urls: 'https://192.168.23.102:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'k8s-master-01=https://192.168.23.101:2380,k8s-master-02=https://192.168.23.102:2380,k8s-master-03=https://192.168.23.103:2380'
initial-cluster-token: 'etcd-k8s-cluster'
initial-cluster-state: 'new'
strict-reconfig-check: false
enable-v2: true
enable-pprof: true
proxy: 'off'
proxy-failure-wait: 5000
proxy-refresh-interval: 30000
proxy-dial-timeout: 1000
proxy-write-timeout: 5000
proxy-read-timeout: 0
client-transport-security:
cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
client-cert-auth: true
trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
auto-tls: true
peer-transport-security:
cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
peer-client-cert-auth: true
trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
auto-tls: true
debug: false
log-package-levels:
log-outputs: [default]
force-new-cluster: false
EOF
- k8s-master-03配置
cat > /etc/etcd/etcd.config.yml << EOF
name: 'k8s-master-03'
data-dir: /var/lib/etcd
wal-dir: /var/lib/etcd/wal
snapshot-count: 5000
heartbeat-interval: 100
election-timeout: 1000
quota-backend-bytes: 0
listen-peer-urls: 'https://192.168.23.103:2380'
listen-client-urls: 'https://192.168.23.103:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://192.168.23.103:2380'
advertise-client-urls: 'https://192.168.23.103:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'k8s-master-01=https://192.168.23.101:2380,k8s-master-02=https://192.168.23.102:2380,k8s-master-03=https://192.168.23.103:2380'
initial-cluster-token: 'etcd-k8s-cluster'
initial-cluster-state: 'new'
strict-reconfig-check: false
enable-v2: true
enable-pprof: true
proxy: 'off'
proxy-failure-wait: 5000
proxy-refresh-interval: 30000
proxy-dial-timeout: 1000
proxy-write-timeout: 5000
proxy-read-timeout: 0
client-transport-security:
cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
client-cert-auth: true
trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
auto-tls: true
peer-transport-security:
cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'
key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'
peer-client-cert-auth: true
trusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'
auto-tls: true
debug: false
log-package-levels:
log-outputs: [default]
force-new-cluster: false
EOF
- 创建etcd service并启动
cat > /root/etcd.service << EOF
[Unit]
Description=Etcd Service
Documentation=https://coreos.com/etcd/docs/latest/
After=network.target
[Service]
Type=notify
ExecStart=/usr/local/bin/etcd --config-file=/etc/etcd/etcd.config.yml
Restart=on-failure
RestartSec=10
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
Alias=etcd3.service
EOF
#分发配置
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
scp /root/etcd.service root@$IP_HOST:/usr/lib/systemd/system/
echo "------$IP_HOST OK------"
done
- 创建etcd的证书目录
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "mkdir -p /etc/kubernetes/pki/etcd"
ssh root@$IP_HOST "ln -s /etc/etcd/ssl/* /etc/kubernetes/pki/etcd/"
ssh root@$IP_HOST "systemctl daemon-reload && systemctl enable --now etcd && systemctl status etcd"
echo "------$IP_HOST OK------"
done
- 检查集群
export ETCDCTL_API=3
etcdctl --endpoints="192.168.23.103:2379,192.168.23.102:2379,192.168.23.101:2379" \
--cacert=/etc/kubernetes/pki/etcd/etcd-ca.pem \
--cert=/etc/kubernetes/pki/etcd/etcd.pem \
--key=/etc/kubernetes/pki/etcd/etcd-key.pem \
endpoint status --write-out=table
apiserver配置
注意:涉及所有Master节点
所有Master节点创建kube-apiserver service,# 注意,如果不是高可用集群,192.168.23.100改为k8s-master-01的地址。
注意本文档使用的k8s service网段为192.168.0.0/16,该网段不能和宿主机的网段、Pod网段的重复,请按需修改**。**
- k8s-master-01
cat > /usr/lib/systemd/system/kube-apiserver.service << EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/kubernetes/kubernetes
After=network.target
[Service]
ExecStart=/usr/local/bin/kube-apiserver \
--v=2 \
--logtostderr=true \
--allow-privileged=true \
--bind-address=0.0.0.0 \
--secure-port=6443 \
--advertise-address=192.168.23.101 \
--service-cluster-ip-range=192.168.0.0/16 \
--service-node-port-range=30000-32767 \
--etcd-servers=https://192.168.23.101:2379,https://192.168.23.102:2379,https://192.168.23.103:2379 \
--etcd-cafile=/etc/etcd/ssl/etcd-ca.pem \
--etcd-certfile=/etc/etcd/ssl/etcd.pem \
--etcd-keyfile=/etc/etcd/ssl/etcd-key.pem \
--client-ca-file=/etc/kubernetes/pki/ca.pem \
--tls-cert-file=/etc/kubernetes/pki/apiserver.pem \
--tls-private-key-file=/etc/kubernetes/pki/apiserver-key.pem \
--kubelet-client-certificate=/etc/kubernetes/pki/apiserver.pem \
--kubelet-client-key=/etc/kubernetes/pki/apiserver-key.pem \
--service-account-key-file=/etc/kubernetes/pki/sa.pub \
--service-account-signing-key-file=/etc/kubernetes/pki/sa.key \
--service-account-issuer=https://kubernetes.default.svc.cluster.local \
--kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname \
--enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,ResourceQuota \
--feature-gates=LegacyServiceAccountTokenNoAutoGeneration=false \
--authorization-mode=Node,RBAC \
--enable-bootstrap-token-auth=true \
--requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem \
--proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.pem \
--proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client-key.pem \
--requestheader-allowed-names=aggregator \
--requestheader-group-headers=X-Remote-Group \
--requestheader-extra-headers-prefix=X-Remote-Extra- \
--requestheader-username-headers=X-Remote-User
# --token-auth-file=/etc/kubernetes/token.csv
Restart=on-failure
RestartSec=10s
LimitNOFILE=65535
[Install]
WantedBy=multi-user.target
EOF
- k8s-master-02
cat > /usr/lib/systemd/system/kube-apiserver.service << EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/kubernetes/kubernetes
After=network.target
[Service]
ExecStart=/usr/local/bin/kube-apiserver \
--v=2 \
--logtostderr=true \
--allow-privileged=true \
--bind-address=0.0.0.0 \
--secure-port=6443 \
--advertise-address=192.168.23.102 \
--service-cluster-ip-range=192.168.0.0/16 \
--service-node-port-range=30000-32767 \
--etcd-servers=https://192.168.23.101:2379,https://192.168.23.102:2379,https://192.168.23.103:2379 \
--etcd-cafile=/etc/etcd/ssl/etcd-ca.pem \
--etcd-certfile=/etc/etcd/ssl/etcd.pem \
--etcd-keyfile=/etc/etcd/ssl/etcd-key.pem \
--client-ca-file=/etc/kubernetes/pki/ca.pem \
--tls-cert-file=/etc/kubernetes/pki/apiserver.pem \
--tls-private-key-file=/etc/kubernetes/pki/apiserver-key.pem \
--kubelet-client-certificate=/etc/kubernetes/pki/apiserver.pem \
--kubelet-client-key=/etc/kubernetes/pki/apiserver-key.pem \
--service-account-key-file=/etc/kubernetes/pki/sa.pub \
--service-account-signing-key-file=/etc/kubernetes/pki/sa.key \
--service-account-issuer=https://kubernetes.default.svc.cluster.local \
--kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname \
--enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,ResourceQuota \
--feature-gates=LegacyServiceAccountTokenNoAutoGeneration=false \
--authorization-mode=Node,RBAC \
--enable-bootstrap-token-auth=true \
--requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem \
--proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.pem \
--proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client-key.pem \
--requestheader-allowed-names=aggregator \
--requestheader-group-headers=X-Remote-Group \
--requestheader-extra-headers-prefix=X-Remote-Extra- \
--requestheader-username-headers=X-Remote-User
# --token-auth-file=/etc/kubernetes/token.csv
Restart=on-failure
RestartSec=10s
LimitNOFILE=65535
[Install]
WantedBy=multi-user.target
EOF
- k8s-master-03
cat > /usr/lib/systemd/system/kube-apiserver.service << EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/kubernetes/kubernetes
After=network.target
[Service]
ExecStart=/usr/local/bin/kube-apiserver \
--v=2 \
--logtostderr=true \
--allow-privileged=true \
--bind-address=0.0.0.0 \
--secure-port=6443 \
--advertise-address=192.168.23.103 \
--service-cluster-ip-range=192.168.0.0/16 \
--service-node-port-range=30000-32767 \
--etcd-servers=https://192.168.23.101:2379,https://192.168.23.102:2379,https://192.168.23.103:2379 \
--etcd-cafile=/etc/etcd/ssl/etcd-ca.pem \
--etcd-certfile=/etc/etcd/ssl/etcd.pem \
--etcd-keyfile=/etc/etcd/ssl/etcd-key.pem \
--client-ca-file=/etc/kubernetes/pki/ca.pem \
--tls-cert-file=/etc/kubernetes/pki/apiserver.pem \
--tls-private-key-file=/etc/kubernetes/pki/apiserver-key.pem \
--kubelet-client-certificate=/etc/kubernetes/pki/apiserver.pem \
--kubelet-client-key=/etc/kubernetes/pki/apiserver-key.pem \
--service-account-key-file=/etc/kubernetes/pki/sa.pub \
--service-account-signing-key-file=/etc/kubernetes/pki/sa.key \
--service-account-issuer=https://kubernetes.default.svc.cluster.local \
--kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname \
--enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,ResourceQuota \
--feature-gates=LegacyServiceAccountTokenNoAutoGeneration=false \
--authorization-mode=Node,RBAC \
--enable-bootstrap-token-auth=true \
--requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem \
--proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.pem \
--proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client-key.pem \
--requestheader-allowed-names=aggregator \
--requestheader-group-headers=X-Remote-Group \
--requestheader-extra-headers-prefix=X-Remote-Extra- \
--requestheader-username-headers=X-Remote-User
# --token-auth-file=/etc/kubernetes/token.csv
Restart=on-failure
RestartSec=10s
LimitNOFILE=65535
[Install]
WantedBy=multi-user.target
EOF
- 开启kube-apiserver
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl daemon-reload && systemctl enable --now kube-apiserver"
ssh root@$IP_HOST "systemctl status kube-apiserver"
echo "------$IP_HOST OK------"
done
controllerManager配置
注意:涉及所有Master节点
注意本文档使用的k8s Pod网段为172.16.0.0/12,该网段不能和宿主机的网段、k8s Service网段的重复,请按需修改。
所有Master节点配置kube-controller-manager service(所有master节点配置一样)。
- 配置kube-controller-manager service
cat > /root/kube-controller-manager.service << EOF
[Unit]
Description=Kubernetes Controller Manager
Documentation=https://github.com/kubernetes/kubernetes
After=network.target
[Service]
ExecStart=/usr/local/bin/kube-controller-manager \
--v=2 \
--logtostderr=true \
--root-ca-file=/etc/kubernetes/pki/ca.pem \
--cluster-signing-cert-file=/etc/kubernetes/pki/ca.pem \
--cluster-signing-key-file=/etc/kubernetes/pki/ca-key.pem \
--service-account-private-key-file=/etc/kubernetes/pki/sa.key \
--kubeconfig=/etc/kubernetes/controller-manager.kubeconfig \
--feature-gates=LegacyServiceAccountTokenNoAutoGeneration=false \
--leader-elect=true \
--use-service-account-credentials=true \
--node-monitor-grace-period=40s \
--node-monitor-period=5s \
--pod-eviction-timeout=2m0s \
--controllers=*,bootstrapsigner,tokencleaner \
--allocate-node-cidrs=true \
--cluster-cidr=172.16.0.0/12 \
--requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem \
--node-cidr-mask-size=24
Restart=always
RestartSec=10s
[Install]
WantedBy=multi-user.target
EOF
- 分发配置
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
scp /root/kube-controller-manager.service root@$IP_HOST:/usr/lib/systemd/system/
echo "------$IP_HOST OK------"
done
- 启动kube-controller-manager
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl daemon-reload && systemctl enable --now kube-controller-manager"
ssh root@$IP_HOST "systemctl status kube-controller-manager"
echo "------$IP_HOST OK------"
done
sheduler配置
注意:涉及所有Master节点
所有Master节点配置kube-scheduler service(所有master节点配置一样)。
- 配置kube-scheduler service
cat > /root/kube-scheduler.service << EOF
[Unit]
Description=Kubernetes Scheduler
Documentation=https://github.com/kubernetes/kubernetes
After=network.target
[Service]
ExecStart=/usr/local/bin/kube-scheduler \
--v=2 \
--logtostderr=true \
--leader-elect=true \
--authentication-kubeconfig=/etc/kubernetes/scheduler.kubeconfig \
--authorization-kubeconfig=/etc/kubernetes/scheduler.kubeconfig \
--kubeconfig=/etc/kubernetes/scheduler.kubeconfig
Restart=always
RestartSec=10s
[Install]
WantedBy=multi-user.target
EOF
- 分发配置
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
scp /root/kube-scheduler.service root@$IP_HOST:/usr/lib/systemd/system/
echo "------$IP_HOST OK------"
done
- 启动kube-scheduler
for IP_HOST in 192.168.23.10{1..3}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl daemon-reload && systemctl enable --now kube-scheduler"
ssh root@$IP_HOST "systemctl status kube-scheduler"
echo "------$IP_HOST OK------"
done
TLS Bootstrapping配置
注意:只需要在k8s-master-01创建bootstrap
如果不是高可用集群,192.168.23.100:8443改为k8s-master-01的地址,8443改为apiserver的端口,默认是6443。
注意:如果要修改bootstrap.secret.yaml的token-id和token-secret,需要保证下图红圈内的字符串一致的,并且位数是一样的。还要保证上个命令:c8ad9c.2e4d610cf3e7426e与你修改的字符串要一致。
- 创建bootstrap证书
cd /root/k8s-ha-install/bootstrap
#注意此处的地址,按需修改
kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.pem \
--embed-certs=true \
--server=https://192.168.23.100:8443 \
--kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
#注意此处的token,要检查/root/k8s-ha-install/bootstrap/bootstrap.secret.yaml文件中的是否一致
kubectl config set-credentials tls-bootstrap-token-user \
--token=c8ad9c.2e4d610cf3e7426e \
--kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
kubectl config set-context tls-bootstrap-token-user@kubernetes \
--cluster=kubernetes \
--user=tls-bootstrap-token-user \
--kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
kubectl config use-context tls-bootstrap-token-user@kubernetes \
--kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig
- token图示
- 配置kubectl命令
mkdir -p /root/.kube ; cp /etc/kubernetes/admin.kubeconfig /root/.kube/config
- 配置kubectl命令补全
yum -y install bash-completion
source /usr/share/bash-completion/bash_completion
source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> ~/.bashrc
- 查询集群状态
kubectl get cs
# Warning: v1 ComponentStatus is deprecated in v1.19+
# NAME STATUS MESSAGE ERROR
# controller-manager Healthy ok
# scheduler Healthy ok
# etcd-1 Healthy {"health":"true","reason":""}
# etcd-0 Healthy {"health":"true","reason":""}
# etcd-2 Healthy {"health":"true","reason":""}
- 创建bootstrap
cd /root/k8s-ha-install/bootstrap
kubectl create -f bootstrap.secret.yaml
- 分发证书
for IP_HOST in 192.168.23.10{2..5}; do
echo "------$IP_HOST------"
scp /etc/kubernetes/bootstrap-kubelet.kubeconfig root@$IP_HOST:/etc/kubernetes/
echo "------$IP_HOST OK------"
done
kubelet配置
注意:涉及所有节点
如果更改了k8s的service网段,需要更改kubelet-conf.yml 的clusterDNS:配置,改成k8s Service网段的第十个地址,比如192.168.0.10
- 创建目录
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "mkdir -p /var/lib/kubelet /var/log/kubernetes /etc/systemd/system/kubelet.service.d /etc/kubernetes/manifests/"
echo "------$IP_HOST OK------"
done
- 配置kubelet service
cat > /root/kubelet.service << EOF
[Unit]
Description=Kubernetes Kubelet
Documentation=https://github.com/kubernetes/kubernetes
[Service]
ExecStart=/usr/local/bin/kubelet
Restart=always
StartLimitInterval=0
RestartSec=10
[Install]
WantedBy=multi-user.target
EOF
- 如果Runtime为Containerd,请添加如下Kubelet的配置(本次使用的是Containerd所以添加如下配置)
# Runtime为Containerd
cat > /root/10-kubelet.conf << 'EOF'
[Service]
Environment="KUBELET_KUBECONFIG_ARGS=--bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig --kubeconfig=/etc/kubernetes/kubelet.kubeconfig"
Environment="KUBELET_SYSTEM_ARGS=--container-runtime=remote --runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock"
Environment="KUBELET_CONFIG_ARGS=--config=/etc/kubernetes/kubelet-conf.yml"
Environment="KUBELET_EXTRA_ARGS=--node-labels=node.kubernetes.io/node='' "
ExecStart=
ExecStart=/usr/local/bin/kubelet $KUBELET_KUBECONFIG_ARGS $KUBELET_CONFIG_ARGS $KUBELET_SYSTEM_ARGS $KUBELET_EXTRA_ARGS
EOF
- 创建kubelet配置文件
注意此处clusterDNS的IP地址
cat > /root/kubelet-conf.yml << EOF
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
address: 0.0.0.0
port: 10250
readOnlyPort: 10255
authentication:
anonymous:
enabled: false
webhook:
cacheTTL: 2m0s
enabled: true
x509:
clientCAFile: /etc/kubernetes/pki/ca.pem
authorization:
mode: Webhook
webhook:
cacheAuthorizedTTL: 5m0s
cacheUnauthorizedTTL: 30s
cgroupDriver: systemd
cgroupsPerQOS: true
clusterDNS:
- 192.168.0.10
clusterDomain: cluster.local
containerLogMaxFiles: 5
containerLogMaxSize: 10Mi
contentType: application/vnd.kubernetes.protobuf
cpuCFSQuota: true
cpuManagerPolicy: none
cpuManagerReconcilePeriod: 10s
enableControllerAttachDetach: true
enableDebuggingHandlers: true
enforceNodeAllocatable:
- pods
eventBurst: 10
eventRecordQPS: 5
evictionHard:
imagefs.available: 15%
memory.available: 100Mi
nodefs.available: 10%
nodefs.inodesFree: 5%
evictionPressureTransitionPeriod: 5m0s
failSwapOn: true
fileCheckFrequency: 20s
hairpinMode: promiscuous-bridge
healthzBindAddress: 127.0.0.1
healthzPort: 10248
httpCheckFrequency: 20s
imageGCHighThresholdPercent: 85
imageGCLowThresholdPercent: 80
imageMinimumGCAge: 2m0s
iptablesDropBit: 15
iptablesMasqueradeBit: 14
kubeAPIBurst: 10
kubeAPIQPS: 5
makeIPTablesUtilChains: true
maxOpenFiles: 1000000
maxPods: 110
nodeStatusUpdateFrequency: 10s
oomScoreAdj: -999
podPidsLimit: -1
registryBurst: 10
registryPullQPS: 5
resolvConf: /etc/resolv.conf
rotateCertificates: true
runtimeRequestTimeout: 2m0s
serializeImagePulls: true
staticPodPath: /etc/kubernetes/manifests
streamingConnectionIdleTimeout: 4h0m0s
syncFrequency: 1m0s
volumeStatsAggPeriod: 1m0s
EOF
- 分发配置
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
scp /root/kubelet.service $IP_HOST:/usr/lib/systemd/system/
scp /root/10-kubelet.conf $IP_HOST:/etc/systemd/system/kubelet.service.d/
scp /root/kubelet-conf.yml $IP_HOST:/etc/kubernetes/
echo "------$IP_HOST OK------"
done
- 启动kubelet
for IP_HOST in 192.168.23.10{1..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl daemon-reload && systemctl enable --now kubelet"
ssh root@$IP_HOST "systemctl status kubelet"
echo "------$IP_HOST OK------"
done
kube-proxy配置
注意:涉及所有节点
如果不是高可用集群,192.168.23.100:8443改为master01的地址,8443改为apiserver的端口,默认是6443
- 创建证书
cd /root/k8s-ha-install
kubectl -n kube-system create serviceaccount kube-proxy
kubectl create clusterrolebinding system:kube-proxy \
--clusterrole system:node-proxier \
--serviceaccount kube-system:kube-proxy
SECRET=$(kubectl -n kube-system get sa/kube-proxy \
--output=jsonpath='{.secrets[0].name}')
JWT_TOKEN=$(kubectl -n kube-system get secret/$SECRET \
--output=jsonpath='{.data.token}' | base64 -d)
PKI_DIR=/etc/kubernetes/pki
K8S_DIR=/etc/kubernetes
kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.pem \
--embed-certs=true \
--server=https://192.168.23.100:8443 \
--kubeconfig=${K8S_DIR}/kube-proxy.kubeconfig
kubectl config set-credentials kubernetes \
--token=${JWT_TOKEN} \
--kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig
kubectl config set-context kubernetes \
--cluster=kubernetes \
--user=kubernetes \
--kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig
kubectl config use-context kubernetes \
--kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig
- 分发证书
for IP_HOST in 192.168.23.10{2..5}; do
echo "------$IP_HOST------"
scp /etc/kubernetes/kube-proxy.kubeconfig root@$IP_HOST:/etc/kubernetes/kube-proxy.kubeconfig
echo "------$IP_HOST OK------"
done
- 创建kube-proxy service文件
cat > /root/kube-proxy.service << EOF
[Unit]
Description=Kubernetes Kube Proxy
Documentation=https://github.com/kubernetes/kubernetes
After=network.target
[Service]
ExecStart=/usr/local/bin/kube-proxy \
--config=/etc/kubernetes/kube-proxy.yaml \
--v=2
Restart=always
RestartSec=10s
[Install]
WantedBy=multi-user.target
EOF
- 创建kube-proxy的配置
如果更改了集群Pod的网段,需要更改kube-proxy.yaml的clusterCIDR为自己的Pod网段
cat > /root/kube-proxy.yaml << EOF
apiVersion: kubeproxy.config.k8s.io/v1alpha1
bindAddress: 0.0.0.0
clientConnection:
acceptContentTypes: ""
burst: 10
contentType: application/vnd.kubernetes.protobuf
kubeconfig: /etc/kubernetes/kube-proxy.kubeconfig
qps: 5
clusterCIDR: 172.16.0.0/12
configSyncPeriod: 15m0s
conntrack:
max: null
maxPerCore: 32768
min: 131072
tcpCloseWaitTimeout: 1h0m0s
tcpEstablishedTimeout: 24h0m0s
enableProfiling: false
healthzBindAddress: 0.0.0.0:10256
hostnameOverride: ""
iptables:
masqueradeAll: false
masqueradeBit: 14
minSyncPeriod: 0s
syncPeriod: 30s
ipvs:
masqueradeAll: true
minSyncPeriod: 5s
scheduler: "rr"
syncPeriod: 30s
kind: KubeProxyConfiguration
metricsBindAddress: 127.0.0.1:10249
mode: "ipvs"
nodePortAddresses: null
oomScoreAdj: -999
portRange: ""
udpIdleTimeout: 250ms
EOF
- 分发配置
for IP_HOST in 192.168.23.10{2..5}; do
echo "------$IP_HOST------"
scp /root/kube-proxy.service root@$IP_HOST:/usr/lib/systemd/system/
scp /root/kube-proxy.yaml root@$IP_HOST:/etc/kubernetes/
echo "------$IP_HOST OK------"
done
- 启动并验证kube-proxy
for IP_HOST in 192.168.23.10{2..5}; do
echo "------$IP_HOST------"
ssh root@$IP_HOST "systemctl daemon-reload && systemctl enable --now kube-proxy && systemctl status kube-proxy"
echo "------$IP_HOST OK------"
done
集群组件
注意:只需要在k8s-master-01上执行
calico
- 创建calico
注意:涉及k8s-master-01主机
cd /root/k8s-ha-install/calico/
#更改calico的网段,改为自己的Pod网段
sed -i "s#POD_CIDR#172.16.0.0/12#g" calico.yaml
#检查网段是自己的Pod网段
grep "IPV4POOL_CIDR" calico.yaml -A 1
#创建calico
kubectl apply -f calico.yaml
- 查看容器状态
kubectl get po -n kube-system
如果容器状态异常可以使用kubectl describe 或者kubectl logs查看容器的日志。
coredns
- 修改coredns配置
cd /root/k8s-ha-install/
#如果更改了k8s service的网段需要将coredns的serviceIP改成k8s service网段的第十个IP
COREDNS_SERVICE_IP=`kubectl get svc | grep kubernetes | awk '{print $3}'`0
sed -i "s#KUBEDNS_SERVICE_IP#${COREDNS_SERVICE_IP}#g" CoreDNS/coredns.yaml
- 安装coredns
kubectl create -f CoreDNS/coredns.yaml
# serviceaccount/coredns created
# clusterrole.rbac.authorization.k8s.io/system:coredns created
# clusterrolebinding.rbac.authorization.k8s.io/system:coredns created
# configmap/coredns created
# deployment.apps/coredns created
# service/kube-dns created
- 检查容器状态
kubectl get po -n kube-system -l k8s-app=kube-dns
- 更新coredns(根据自身情况更新)
COREDNS_SERVICE_IP=`kubectl get svc | grep kubernetes | awk '{print $3}'`0
git clone https://github.com/coredns/deployment.git
cd deployment/kubernetes
./deploy.sh -s -i ${COREDNS_SERVICE_IP} | kubectl apply -f -
metrice server
- 安装metrics server
cd /root/k8s-ha-install/metrics-server
kubectl create -f .
- 查看状态
kubectl top node
dashboard
- 安装dashboard
cd /root/k8s-ha-install/dashboard/
kubectl create -f .
- 安装dashboard最新版
官方GitHub地址:https://github.com/kubernetes/dashboard
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.3/aio/deploy/recommended.yaml
- 创建管理员用户
cat > admin.yaml << EOF
apiVersion: v1
kind: ServiceAccount
metadata:
name: admin-user
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: admin-user
annotations:
rbac.authorization.kubernetes.io/autoupdate: "true"
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: admin-user
namespace: kube-system
EOF
kubectl apply -f admin.yaml -n kube-system
- dashboard的svc为NodePort
kubectl edit svc kubernetes-dashboard -n kubernetes-dashboard
将ClusterIP更改为NodePort(如果已经为NodePort忽略此步骤)
- 查看dashboard的端口
kubectl get svc kubernetes-dashboard -n kubernetes-dashboard
- 查看登录密码
kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}')
- 登录dashboard设置
在谷歌浏览器(Chrome)启动文件中加入启动参数,用于解决无法访问Dashboard的问题,参考图:
- 访问并登录dashboard
集群验证
查看集群中所有容器
查看集群中所有容器是否启动
kubectl get pod --all-namespaces
查看集群中主要Service
- 查看Cluster的Service
kubectl get service
- 查看DNS的Service
kubectl get service -n kube-system
查看集群中节点网络是否通
- 查看集群中pod运行节点
kubectl get pod --all-namespaces -owide
- ping测试任意ip地址
ping 83.12.151.130
查看集群中所有节点状态
kubectl get nodes
验证要求
- Pod必须能解析Service
- Pod必须能解析跨namespace的Service
- 每个节点都必须要能访问Kubernetes的kubernetes svc 443和kube-dns的service 53
- Pod和Pod之前要能通
- 同namespace能通信
- 跨namespace能通信
- 跨机器能通信