一)、部署K8S集群的两种方式

1、kubeadm和二进制

  • kubeadm
    • kubeadm是一个K8S部署工具,提供kubeadm init和kubeadm join,用于快速部署Kubernetes集群。kubeadm虽然降低了部署门槛,但是kubeadm部署的kubernetes证书时间只有1年,一年后需另外升级证书,后期维护比较麻烦。
  • 二进制包
    • 从Github下载发行版的二进制包,手动部署每个组件,组成Kubernetes集群。二进制手动部署困难,但是证书时间可以自己配置,后期方便维护。

2、环境准备

服务器配置要求:

  • 最低配置:2核CPU、2G内存、40G硬盘

K8S高可用服务器规划:

角色IP组件
k8s-master292.168.211.130kube-apiserver,kube-controller-manager,kube-scheduler,kubelet,kube-proxy,docker,etcd,nginx,keepalived
k8s-master1172.18.152.221kube-apiserver,kube-controller-manager,kube-scheduler,kubelet,kube-proxy,docker,nginx,keepalived
k8s-node1172.18.152.228kubelet,kube-proxy,docker,etcd
k8s-node2172.18.152.229kubelet,kube-proxy,docker,etcd
负载均衡器IPVIP

K8S单master服务器规划

角色IP组件
k8s-master1172.18.152.221kube-apiserver,kube-controller-manager,kube-scheduler,etcd
k8s-node1172.18.152.228kubelet,kube-proxy,docker,etcd
k8s-node2172.18.152.229kubelet,kube-proxy,docker,etcd

3、系统初始化配置

本次实验所用的系统和组件版本

  • 系统:Centos7
  • etcd:3.5.4
  • docker:20.10.9
  • kubernetes:1.23
  • cfssl:1.2.0
  • calico:3.15.1
  • CoreDNS

链接:https://pan.baidu.com/s/1sYEZHXiqs1boY4ibn28-3g?pwd=yutk

# 关闭防火墙   (所有机器上执行)
systemctl stop firewalld
systemctl disable firewalld

# 关闭selinux   (所有机器上执行)
sed -i 's/enforcing/disabled/' /etc/selinux/config

# 关闭swap   (所有机器上执行)/etc/fstab配置文件下注释掉带有swap的那一行

# 设置主机名   (所有机器上执行)
hostnamectl set-hostname k8s-master1
hostnamectl set-hostname k8s-node1
hostnamectl set-hostname k8s-node2

# 执行bash命令使主机名生效
bash

# 在master 添加hosts
cat >> /etc/hosts << EOF
172.18.152.221    k8s-master1
172.18.152.228    k8s-node1
172.18.152.229	  k8s-node2
EOF

# 将桥接的IPv4流量传递到iptables的链   (所有机器上执行)
cat >> /etc/sysctl.d/k8s.conf << EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl --system

# 时间同步   (所有机器上执行)
yum install ntpdate -y
ntpdate time.windows.com

二)、Etcd集群部署

Etcd是一个分布式键值存储系统,用于共享配置和服务发现。准备一个Etcd数据库,可以解决Etcd单点故障。这里采用3台机器搭建集群,可以容忍一台机器故障。

节点名称IP
etcd-1172.18.152.221
etcd-2172.18.152.228
etcd-3172.18.152.229
Etcd集群可以与k8s节点机器复用,也可以独立于k8s集群外部署,只要能连接到apiserver上就行。

1、准备cfssl证书生成工具

cfssl是一个开源的证书管理工具,使用json文件生成证书。

wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64
chmod +x cfssl*
mv cfssl_linux-amd64 cfssl
mv cfssljson_linux-amd64 cfssljson
mv cfssl-certinfo_linux-amd64 cfssl-certinfo
mv cfssl* /usr/bin/		#将下载好的三个cfssl二进制文件移到可执行文件下,就可以直接使用

2、生成Etcd证书 (自签证书颁发机构 CA)

# 创建工作目录
mkdir ~/TLS/etcd -p
cd ~/TLS/etcd
cat > ca-config.json << EOF
{
  "signing": {
    "default": {
      "expiry": "87600h"
  },
  "profiles": {
    "kubernetes": {
       "expiry": "87600h",
       "usages": [
         "signing",
         "key encipherment",
         "server auth",
         "client auth"
       ]
     }
   }
 }
}
EOF
----------------------------------------
cat > ca-csr.json << EOF 
{
    "CN": "etcd",
    "key": {
       "algo": "rsa",
       "size": 2048
     },
     "names": [
        {
          "C": "CN",
          "L": "ShenZhen",
          "ST": "ShenZhen"
        }
    ]
}
EOF
# 生成根证书
cfssl gencert -initca ca-csr.json | cfssljson -bare ca -
# 在目录下查看是否生成了 ca-key.pem和ca.pem这两个根证书

3、使用自签CA签发Etcd HTTPS证书

# 创建证书申请文件
cat > server-csr.json << EOF
{
    "CN": "etcd",
    "hosts": [
    "172.18.152.221",
    "172.18.152.228",
    "172.18.152.229"
   
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C:": "CN",
            "L": "ShenZhen",
            "ST": "ShenZhen"
        }
    ]
}
EOF
# hosts字段中的IP是所有etcd节点集群内部通信的IP地址,缺一不可。如果后面有etcd扩容的需求,建议这里多预留几个IP地址方便后期扩容。
# 生成证书
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes server-csr.json | cfssljson -bare server
# 执行完成后会生成 server-key.pem  server.pem 这两个文件

4、从Github官网下载Etcd二进制文件

https://github.com/etcd-io/etcd/releases/download/v3.5.4/etcd-v3.5.4-linux-amd64.tar.gz

5、部署Etcd集群

# 创建工作目录并解压二进制包
mkdir /usr/local/k8s/etcd/{bin,cfg,ssl} -p
tar -zxf etcd-v3.5.4-linux-amd64.tar.gz
mv etcd-v3.5.4-linux-amd64/{etcd,etcdctl} /usr/local/k8s/etcd/bin/	

6、创建Etcd配置文件

cat > /usr/local/k8s/etcd/cfg/etcd.conf << EOF
#[Member]
ETCD_NAME="etcd-01"
ETCD_DATA_DIR="/var/lib/etcd/default.etcd"
ETCD_LISTEN_PEER_URLS="https://172.18.152.221:2380"
ETCD_LISTEN_CLIENT_URLS="https://172.18.152.221:2379"

#[Clustering]
ETCD_INITIAL_ADVERTISE_PEER_URLS="https://172.18.152.221:2380"
ETCD_ADVERTISE_CLIENT_URLS="https://172.18.152.221:2379"
ETCD_INITIAL_CLUSTER="etcd-01=https://172.18.152.221:2380,etcd-02=https://172.18.152.228:2380,etcd-03=https://172.18.152.229:2380"
ETCD_INITIAL_CLUSTER_TOKEN="k8s-etcd-cluster"
ETCD_INITIAL_CLUSTER_STATE="new"
ETCD_ENABLE_V2="true"
EOF
# 2380:是用于集群中通讯的端口
# 2379:是用于客户端连接etcd做数据的读取写入的端口
# ETCD_NAME:节点名称,集群中是唯一的
# ETCD_DATA_DIR:数据目录
# ETCD_LISTEN_PEER_URLS:集群 通讯监听地址
# ETCD_LISTEN_CLIENT_URLS:客户端访问监听地址
# ETCD_INITIAL_ADVERTISE_PEER_URLS:集群通告地址
# ETCD_ADVERTISE_CLIENT_URLS:客户端通告地址
# ETCD_INITIAL_CLUSTER:集群组件的三个节点IP和端口
# ETCD_INITIAL_CLUSTER_TOKEN:集群之间通讯的token
# ETCD_INITIAL_CLUSTER_STATE:加入集群的状态,new是新集群,existing是加入已有集群
# ETCD_ENABLE_V2:兼容flannel

7、systemd管理Etcd

cat > /usr/lib/systemd/system/etcd.service << EOF
[Unit]
Description=Etcd Server
After=network.target
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
EnvironmentFile=/usr/local/k8s/etcd/cfg/etcd.conf
ExecStart=/usr/local/k8s/etcd/bin/etcd \\
--cert-file=/usr/local/k8s/etcd/ssl/server.pem \\
--key-file=/usr/local/k8s/etcd/ssl/server-key.pem \\
--peer-cert-file=/usr/local/k8s/etcd/ssl/server.pem \\
--peer-key-file=/usr/local/k8s/etcd/ssl/server-key.pem \\
--trusted-ca-file=/usr/local/k8s/etcd/ssl/ca.pem \\
--peer-trusted-ca-file=/usr/local/k8s/etcd/ssl/ca.pem \\
--logger=zap
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF


# Description:给出描述
# After:启动顺序和依赖关系,如果表示network.target,那么etcd应该在它们后面启动
# Wants:依赖关系,表示network-online.target和etcd存在“弱依赖”关系,即使etcd启动失败或停止,都不影响network-online.target执行
# [service]:启动行为
# EnvironmentFile:指定当前服务的环境参数文件
# ExecStart:定义进程启动时执行的命令
# Restart:Restart设置为on-failure,表示任何意外的失败,都将重启etcd,如果正常停止,就不会被重启
# WantedBy:表示该服务所在的Target,Target表示一组服务。当在执行systemctl enable etcd时,etcd的一个符号链接就会放在/etc/systemd/system目录下的multi-user.target.wants子目录中。

# 将之前生成的ca证书和server证书拷贝到工作目录下
cp ~/TLS/etcd/ca*pem /usr/local/k8s/etcd/ssl/
cp ~/TLS/etcd/server*pem /usr/local/k8s/etcd/ssl/

8、启动Etcd集群

systemctl daemon-reload
systemctl start etcd
systemctl enable etcd
systemctl status etcd
# 这里etcd会一直在启动,原因是另外2个节点的etcd并没有启动,查看日志会显示另外两个节点连接被拒绝
# journalctl -u etcd--->  查看etcd日志

9、更改其他节点上的etcd配置

scp -r /usr/local/k8s/ root@172.18.152.228:/usr/local/k8s/
scp -r /usr/local/k8s/ root@172.18.152.229:/usr/local/k8s/
scp /usr/lib/systemd/system/etcd.service root@172.18.152.228:/usr/lib/systemd/system/
scp /usr/lib/systemd/system/etcd.service root@172.18.152.229:/usr/lib/systemd/system/
# 在另外两台节点上更改etcd配置文件

#[Member]
cat /usr/local/k8s/etcd/cfg/etcd.conf 
ETCD_NAME="xxxxxxxxx"
# 在node1节点上修改成etcd-02,node2节点上修改成etcd-03
ETCD_DATA_DIR="/var/lib/etcd/default.etcd"
ETCD_LISTEN_PEER_URLS="https://xxxxxxxxx:2380" 
# 涉及了IP地址的都要更改为当前机器的IP地址
ETCD_LISTEN_CLIENT_URLS="https://xxxxxxxxx:2379"

#[Clustering]
ETCD_INITIAL_ADVERTISE_PEER_URLS="https://xxxxxxxxx:2380"
ETCD_ADVERTISE_CLIENT_URLS="https://xxxxxxxxx:2379"
ETCD_INITIAL_CLUSTER="etcd-01=https://192.168.211.150:2380,etcd-02=https://192.168.211.152:2380,etcd-03=https://192.168.211.153:2380"
ETCD_INITIAL_CLUSTER_TOKEN="k8s-etcd-cluster"
ETCD_INITIAL_CLUSTER_STATE="new"
ETCD_ENABLE_V2="true"

启动etcd并设置开机自启动步骤同上

10、查看集群状态

ETCDCTL_API=3 /usr/local/k8s/etcd/bin/etcdctl --cacert=/usr/local/k8s/etcd/ssl/ca.pem --cert=/usr/local/k8s/etcd/ssl/server.pem --key=/usr/local/k8s/etcd/ssl/server-key.pem --endpoints="https://172.18.152.221:2379,https://172.18.152.228:2379,https://172.18.152.229:2379" endpoint health --write-out=table

+------------------------------+--------+-------------+-------+
|           ENDPOINT           | HEALTH |    TOOK     | ERROR |
+------------------------------+--------+-------------+-------+
| https://192.168.211.153:2379 |   true |   10.9468ms |       |
| https://192.168.211.150:2379 |   true | 11.416038ms |       |
| https://192.168.211.152:2379 |   true | 10.705467ms |       |
+------------------------------+--------+-------------+-------+
# 若集群状态都为true,则表示etcd集群已搭建完成

ETCDCTL_API=3 /usr/local/k8s/etcd/bin/etcdctl --cacert=/usr/local/k8s/etcd/ssl/ca.pem --cert=/usr/local/k8s/etcd/ssl/server.pem --key=/usr/local/k8s/etcd/ssl/server-key.pem --endpoints="https://172.18.152.221:2379,https://172.18.152.228:2379,https://172.18.152.229:2379" member list
412173e1fc6059aa, started, etcd-03, https://172.18.152.229:2380, https://172.18.152.229:2379, false
4eb70443fe11f7c1, started, etcd-01, https://172.18.152.221:2380, https://172.18.152.221:2379, false
eb9ca63f86e66198, started, etcd-02, https://172.18.152.228:2380, https://172.18.152.228:2379, false
# 查询etcd状态和节点id

三)、docker安装

1、解压docker二进制

docker需要在所有节点上运行,需要将docker下载到其他节点上,然后执行如下命令

wget https://download.docker.com/linux/static/stable/x86_64/docker-20.10.9.tgz

tar -zxf docker-20.10.9.tgz

mv docker/* /usr/bin/

2、制作system来管理docker

cat > /usr/lib/systemd/system/docker.service << EOF
[Unit]
Description=Docker program startup management
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target

[Service]
Type=notify
ExecStart=/usr/bin/dockerd
ExecReload=/bin/kill -s HUP
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TimeoutStartSec=0
Delegate=yes
KillMode=process
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s

[install]
WantedBy=multi-user.target
EOF

3、配置镜像下载加速器

mkdir /etc/docker

cat > /etc/docker/daemon.json << EOF
{
  "registry-mirrors": ["https://b9pmyelo.mirror.aliyuncs.com"]
}
EOF

4、启动docker并设置开机自启

systemctl daemon-reload
systemctl start docker
systemctl enable docker

docker info
# 使用docker info命令没有报错,就说明docker已经正常运行,或者pull一个容器
,使用命令:
docker pull nginx

# 提前将阿里云的镜像下载,在所有节点上运行,否则后面master部署网络时会连接不上
docker pull registry.cn-hangzhou.aliyuncs.com/google-containers/pause-amd64:3.0

四)、部署master

1、生成kube-apiserver证书

mkdir ~/TLS/k8s
cd ~/TLS/k8s

# 自签证书颁发机构
cat > ca-config.json << EOF
{
  "signing": {
    "default": {
      "expiry": "87600h"
    },
    "profiles": {
      "kubernetes": {
         "expiry": "87600h",
         "usages": [
            "signing",
            "key encipherment",
            "server auth",
            "client auth"
        ]
      }
    }
  }
}
EOF

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

2、生成证书

cfssl gencert -initca ca-csr.json | cfssljson -bare ca -
# 生成证书 ca.pem和ca-key.pem 文件

3、使用自签证书签发kube-apiserver HTTP证书

# 创建证书申请文件
cat > server-csr.json << EOF
{
    "CN": "kubernetes",
    "hosts": [
      "10.0.0.1",
      "127.0.0.1",
      "172.18.152.221",
      "172.18.152.228",
      "172.18.152.229",
      "kubernetes",
      "kubernetes.default",
      "kubernetes.default.svc",
      "kubernetes.default.svc.cluster",
      "kubernetes.default.svc.cluster.local"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "L": "ShenZhen",
            "ST": "ShenZhen",
            "O": "k8s",
            "OU": "System"
        }
    ]
}
EOF
# hosts字段中为了考虑扩容,可以多写几个IP地址,211.88 IP是VIP。

4、生成证书

cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes server-csr.json | cfssljson -bare server
# 会生成 server.pem和server-key.pem文件

5、下载kubernetes

# 二进制下载地址,选择版本后下载server中tar.gz包就可以了
https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/
# 从github官网下载kubernetes 1.23.10版本
wget https://dl.k8s.io/v1.23.10/kubernetes-server-linux-amd64.tar.gz

6、解压二进制包

mkdir /usr/local/k8s/kubernetes/{bin,cfg,ssl,logs} -p

tar -zxf kubernetes-server-linux-amd64.tar.gz

cd kubernetes/server/bin/

cp kube-apiserver kube-scheduler kube-controller-manager /usr/local/k8s/kubernetes/bin/

cp kubectl  /usr/bin/

7、部署kube-apiserver

cat > /usr/local/k8s/kubernetes/cfg/kube-apiserver.conf << EOF
KUBE_APISERVER_OPTS="--allow-privileged=true \\
--feature-gates=RemoveSelfLink=false \\
--etcd-servers=https://172.18.152.221:2379,https://172.18.152.228:2379,https://172.18.152.229:2379 \\
--bind-address=172.18.152.221 \\
--secure-port=6443 \\
--advertise-address=172.18.152.221 \\
--service-cluster-ip-range=10.0.0.0/24 \\
--enable-admission-plugins=NodeRestriction \\
--authorization-mode=RBAC,Node \\
--enable-bootstrap-token-auth=true \\
--token-auth-file=/usr/local/k8s/kubernetes/cfg/token.csv \\
--service-node-port-range=30000-32767 \\
--kubelet-client-certificate=/usr/local/k8s/kubernetes/ssl/server.pem \\
--kubelet-client-key=/usr/local/k8s/kubernetes/ssl/server-key.pem \\
--tls-cert-file=/usr/local/k8s/kubernetes/ssl/server.pem  \\
--tls-private-key-file=/usr/local/k8s/kubernetes/ssl/server-key.pem \\
--client-ca-file=/usr/local/k8s/kubernetes/ssl/ca.pem \\
--service-account-key-file=/usr/local/k8s/kubernetes/ssl/ca-key.pem \\
--service-account-issuer=api \\
--service-account-signing-key-file=/usr/local/k8s/kubernetes/ssl/ca-key.pem \\
--etcd-cafile=/usr/local/k8s/etcd/ssl/ca.pem \\
--etcd-certfile=/usr/local/k8s/etcd/ssl/server.pem \\
--etcd-keyfile=/usr/local/k8s/etcd/ssl/server-key.pem \\
--requestheader-client-ca-file=/usr/local/k8s/kubernetes/ssl/ca.pem \\
--proxy-client-cert-file=/usr/local/k8s/kubernetes/ssl/server.pem \\
--proxy-client-key-file=/usr/local/k8s/kubernetes/ssl/server-key.pem \\
--requestheader-allowed-names=kubernetes \\
--requestheader-extra-headers-prefix=X-Remote-Extra- \\
--requestheader-group-headers=X-Remote-Group \\
--requestheader-username-headers=X-Remote-User \\
--enable-aggregator-routing=true \\
--audit-log-maxage=30 \\
--audit-log-maxbackup=3 \\
--audit-log-maxsize=100 \\
--audit-log-path=/usr/local/k8s/kubernetes/logs/k8s-audit.log"
EOF
# \\:第一个\是转义符、第二个\是换行符
# feature-gates=RemoveSelfLink=false: K8S1.20后基于对性能和统一apiserver调用方式,移除了对SelfLink的支持,而NFS需要SelfLink的支持
# servers:连接etcd的地址
# bind-address:apiserver监听的IP地址
# secure-port:监听的端口
# advertise-address:集群通讯的IP
# allow-privileged:启用授权
# service-cluster-ip-range:service虚拟IP地址段
# enable-admission-plugins:准入控制插件
# authorization-mode:授权模式
# enable-bootstrap-token-auth:启用 bootstrap-tokenren认证,为了让node节点kubelet自由的颁发证书
# token-auth-file:token文件
# service-node-port-range:server分配的端口范围
# kubelet-client-xxxxx:apiserver访问kubelet客户端的证书
# tls-xxxx-file:apiserver https证书
# service-account-issuer=api和service-account-signing-key-file:这是1.20版本后新增的参数,必须要加上
# etcd-xxxfile:连接etcd集群证书
# audit-log-xxx:审计日志
# requestheader-xxx,proxy-xxx,enable-aggregator-xxx:启动聚合层相关配置

8、拷贝证书到配置文件中

cp ~/TLS/k8s/server*pem /usr/local/k8s/kubernetes/ssl/
cp ~/TLS/k8s/ca*pem /usr/local/k8s/kubernetes/ssl/

9、创建配置文件中的token文件

head -c 16 /dev/urandom | od -An -t x | tr -d ' '
# 先生成Token,然后将下面的token给换成你自己生成的
cat > /usr/local/k8s/kubernetes/cfg/token.csv << EOF
9c96a7bacf3bf22893f55d7cba1e936b,kubelet-bootstrap,10001,"system:node-bootstrapper"
EOF
# 格式:token,用户名,UID,用户组

10、systemd管理apiserver

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

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

[Install]
WantedBy=multi-user.target
EOF

11、启动apiserver并开机自启动

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

五)、部署kube-controller-manager

1、创建kube-controller-manager.conf配置文件

cat > /usr/local/k8s/kubernetes/cfg/kube-controller-manager.conf << EOF
KUBE_CONTROLLER_MANAGER_OPTS="--leader-elect=true \\
--kubeconfig=/usr/local/k8s/kubernetes/cfg/kube-controller-manager.kubeconfig \\
--bind-address=127.0.0.1 \\
--allocate-node-cidrs=true \\
--cluster-cidr=10.244.0.0/16 \\
--service-cluster-ip-range=10.0.0.0/24 \\
--cluster-signing-cert-file=/usr/local/k8s/kubernetes/ssl/ca.pem \\
--cluster-signing-key-file=/usr/local/k8s/kubernetes/ssl/ca-key.pem  \\
--root-ca-file=/usr/local/k8s/kubernetes/ssl/ca.pem \\
--service-account-private-key-file=/usr/local/k8s/kubernetes/ssl/ca-key.pem \\
--cluster-signing-duration=87600h0m0s"
EOF
# leader-elect:当该组件启动多个时,自动选举
# kubeconfig:连接api-server的配置文件
# bind-address:监听地址
# allocate-node-cidrs,cluster-cidr,service-cluster-ip-range:使用cni涉及的网段
# cluster-xxx-file,root-xxx-file:为kubelet颁发的证书所需要的ca
# service-account-private-key-file:service-account的私钥文件
# cluster-signing-duration:kubelet颁发证书的有效期

2、生成kubeconfig文件

cd ~/TLS/k8s

# 生成证书文件请求
cat > kube-controller-manager-csr.json << EOF
{
  "CN": "system:kube-controller-manager",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "ShenZhen", 
      "ST": "ShenZhen",
      "O": "system:masters",
      "OU": "System"
    }
  ]
}
EOF

3、生成证书

cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kube-controller-manager-csr.json | cfssljson -bare kube-controller-manager
# 会生成 kube-controller-manager-key.pem和kube-controller-manager.pem文件

4、生成kubeconfig文件

# KUBE_CONFIG:指定kubeconfig放在哪个文件下
# KUBE_APISERVER:连接APIserver的地址和端口
# 以下是shell命令,直接复制在终端执行,执行完成后会生成kube-controller-manager.kubeconfig文件
# --------------------------------------------
KUBE_CONFIG="/usr/local/k8s/kubernetes/cfg/kube-controller-manager.kubeconfig"
KUBE_APISERVER="https://172.18.152.221:6443"

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

5、systemd管理kube-controller-manager.service

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

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

[Install]
WantedBy=multi-user.target
EOF

6、启动并设置开启自启

systemctl daemon-reload
systemctl start kube-controller-manager
systemctl enable kube-controller-manager
systemctl status kube-controller-manager

六)、部署kube-scheduler

1、创建kube-scheduler.conf配置文件

cat > /usr/local/k8s/kubernetes/cfg/kube-scheduler.conf << EOF
KUBE_SCHEDULER_OPTS="--leader-elect \\
--kubeconfig=/usr/local/k8s/kubernetes/cfg/kube-scheduler.kubeconfig \\
--bind-address=127.0.0.1"
EOF

2、生成kubeconfig证书

cd ~/TLS/k8s

cat > kube-scheduler-csr.json << EOF
{
  "CN": "system:kube-scheduler",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "ShenZhen",
      "ST": "ShenZhen",
      "O": "system:masters",
      "OU": "System"
    }
  ]
}
EOF

3、生成证书

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

4、生成kubeconfig文件

KUBE_CONFIG="/usr/local/k8s/kubernetes/cfg/kube-scheduler.kubeconfig"
KUBE_APISERVER="https://172.18.152.221:6443"

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

5、systemd管理scheduler

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

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

[Install]
WantedBy=multi-user.target
EOF

6、启动并设置开机自启

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

7、查看集群状态

cd ~/TLS/k8s

# 生成kubectl连接集群的证书
cat > admin-csr.json <<EOF
{
  "CN": "admin",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "ShenZhen",
      "ST": "ShenZhen",
      "O": "system:masters",
      "OU": "System"
    }
  ]
}
EOF

cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes admin-csr.json | cfssljson -bare admin
# 生成 admin-key.pem和admin.pem 文件

8、生成kubeconfig配置文件

mkdir /root/.kube

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

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

配置完成后,可以用kubectl命令查看master节点上controller-manager和scheduler组件的状态

kubectl get cs
Warning: v1 ComponentStatus is deprecated in v1.19+
NAME                 STATUS    MESSAGE                         ERROR
controller-manager   Healthy   ok                              
scheduler            Healthy   ok                              
etcd-2               Healthy   {"health":"true","reason":""}   
etcd-0               Healthy   {"health":"true","reason":""}   
etcd-1               Healthy   {"health":"true","reason":""}  

9、授权kubelet-bootstrap用户允许请求证书

cd ~/TLS/k8s/

kubectl create clusterrolebinding kubelet-bootstrap \
--clusterrole=system:node-bootstrapper \
--user=kubelet-bootstrap
# 将之前kubelet-bootstrap用户绑定到system:node-bootstrapper这个角色里面,这个角色具备了kubelet最小权限访问api-server去颁发证书
#---------------------------------------------------
# 如果部署错误,可以使用下面命令进行删除
# kubectl delete clusterrolebinding kubelet-bootstrap

七)、部署Worker node

1、为另外两个节点创建worker node工作目录

# mkdir /usr/local/k8s/kubernetes/{bin,cfg,ssl,logs} -p

cd /root/kubernetes/server/bin/

cp kubelet kube-proxy /usr/local/k8s/kubernetes/bin

2、部署kubelet

cat > /usr/local/k8s/kubernetes/cfg/kubelet.conf << EOF
KUBELET_OPTS="--hostname-override=k8s-master1 \\
--network-plugin=cni \\
--kubeconfig=/usr/local/k8s/kubernetes/cfg/kubelet.kubeconfig \\
--bootstrap-kubeconfig=/usr/local/k8s/kubernetes/cfg/bootstrap.kubeconfig \\
--config=/usr/local/k8s/kubernetes/cfg/kubelet-config.yml \\
--cert-dir=/usr/local/k8s/kubernetes/ssl \\
--pod-infra-container-image=registry.cn-hangzhou.aliyuncs.com/google-containers/pause-amd64:3.0"
EOF

# hostname-override:显示名称,集群中唯一
# network-plugin:启用CNI
# kubeconfig:空路径,会自动生成,后面用于连接apiserver
# bootstrap-kubeconfig:首次启动向apiserver申请证书
# config:配置参数文件
# cert-dir:kubelet证书生成目录
# pod-infra-container-image:管理Pod网络容器的镜像

3、配置参数文件

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

4、生成kubelet初次加入集群引导kubeconfig文件

KUBE_CONFIG="/usr/local/k8s/kubernetes/cfg/bootstrap.kubeconfig"
KUBE_APISERVER="https://172.18.152.221:6443"
TOKEN="9c96a7bacf3bf22893f55d7cba1e936b"

# 生成 kubelet bootstrap kubeconfig 配置文件
kubectl config set-cluster kubernetes \
  --certificate-authority=/usr/local/k8s/kubernetes/ssl/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials "kubelet-bootstrap" \
  --token=${TOKEN} \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \
  --cluster=kubernetes \
  --user="kubelet-bootstrap" \
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}
# 需要和上面的token保持一致

5、systemd管理kubelet

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

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

[Install]
WantedBy=multi-user.target
EOF

6、设置开机自启动

systemctl daemon-reload
systemctl start kubelet
systemctl enable kubelet
systemctl status kubelet

7、批准kubelet证书申请并加入集群

# 查看kubelet证书请求
kubectl get csr
NAME                                                   AGE   SIGNERNAME                                    REQUESTOR           CONDITION
node-csr-XrB-YiOEAjUnkaIpk0PfM0WDE8NxTSEBwnZWkXV3SRk   16s   kubernetes.io/kube-apiserver-client-kubelet   kubelet-bootstrap   Pending

#同意申请
kubectl certificate approve node-csr-XrB-YiOEAjUnkaIpk0PfM0WDE8NxTSEBwnZWkXV3SRk

# 查看节点
kubectl get node
NAME          STATUS     ROLES    AGE   VERSION
k8s-master1   NotReady   <none>   6s    v1.23.10

八)、部署kube-porxy

1、创建配置文件

cat > /usr/local/k8s/kubernetes/cfg/kube-proxy.conf << EOF
KUBE_PROXY_OPTS="--config=/usr/local/k8s/kubernetes/cfg/kube-proxy-config.yml"
EOF

2、配置参数文件

cat > /usr/local/k8s/kubernetes/cfg/kube-proxy-config.yml << EOF
kind: KubeProxyConfiguration
apiVersion: kubeproxy.config.k8s.io/v1alpha1
bindAddress: 0.0.0.0
metricsBindAddress: 0.0.0.0:10249
clientConnection:
  kubeconfig: /usr/local/k8s/kubernetes/cfg/kube-proxy.kubeconfig
hostnameOverride: k8s-master1
clusterCIDR: 10.244.0.0/16
EOF

3、生成kube-proxy.kubeconfig文件

cd ~/TLS/k8s

# 创建证书请求文件
cat > kube-proxy-csr.json << EOF
{
  "CN": "system:kube-proxy",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "ShenZhen",
      "ST": "ShenZhen",
      "O": "k8s",
      "OU": "System"
    }
  ]
}
EOF

4、生成证书

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

# 生成kubeconfig文件
KUBE_CONFIG="/usr/local/k8s/kubernetes/cfg/kube-proxy.kubeconfig"
KUBE_APISERVER="https://172.18.152.221:6443"

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

5、systemd管理kube-proxy

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

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

[Install]
WantedBy=multi-user.target
EOF

6、设置开机自启

systemctl daemon-reload
systemctl start kube-proxy
systemctl status kube-proxy
systemctl enable kube-proxy
ps -ef | grep kube-proxy

九、部署网络组件(calico)

1、部署 calico

# 下载calico
# 修改配置文件中定义的Pod网络(CALICO_IPV4POOL_CIDR),           
 # - name: CALICO_IPV4POOL_CIDR
            #   value: "192.168.0.0/16"
#将这两行取消注释,然后将192.168.0.0/16这个网段替换成上方kube-controller-manager配置文件指定的cluster-cidr网段一样
kubectl apply -f calico.yaml
kubectl get pods -n kube-system

2、授权apiserver访问kubelet

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

kubectl apply -f apiserver-to-kubelet-rbac.yaml

10、新增Worker Node

1、将master节点上准备好的node文件拷贝到另外两台节点上

scp -r /usr/local/k8s/kubernetes root@172.18.152.228:/usr/local/k8s/

scp -r /usr/lib/systemd/system/{kubelet,kube-proxy}.service root@172.18.152.228:/usr/lib/systemd/system

scp /usr/local/k8s/kubernetes/ssl/ca.pem root@172.18.152.228:/usr/local/k8s/kubernetes/ssl

scp -r /usr/local/k8s/kubernetes root@172.18.152.229:/usr/local/k8s/

scp -r /usr/lib/systemd/system/{kubelet,kube-proxy}.service root@172.18.152.229:/usr/lib/systemd/system

scp /usr/local/k8s/kubernetes/ssl/ca.pem root@172.18.152.229:/usr/local/k8s/kubernetes/ssl

2、 删除kubelet证书和kubeconfig文件

rm -f /usr/local/k8s/kubernetes/cfg/kubelet.kubeconfig 
rm -f /usr/local/k8s/kubernetes/ssl/kubelet*
# 这几个文件是证书申请审批后自动生成的,每个Node不同,必须删除

3、修改主机名

vim /usr/local/k8s/kubernetes/cfg/kubelet.conf
--hostname-override=k8s-node1

vim /usr/local/k8s/kubernetes/cfg/kube-proxy-config.yml
hostnameOverride: k8s-node1

4、启动kubelet和kube-proxy

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

5、在master节点上给node1节点批准证书请求

[root@k8s-master1 ~]# kubectl get csr
NAME                                                   AGE    SIGNERNAME                                    REQUESTOR           REQUESTEDDURATION   CONDITION
node-csr-6w2Smj1kBlR9TYG4ZspUrzsaDNLJ3IFMGeDdblevMTE   112s   kubernetes.io/kube-apiserver-client-kubelet   kubelet-bootstrap   <none>              Pending
# 状态为pending,表示并未批准,状态为Approved,Issued,表示已经批准

kubectl certificate approve node-csr-6w2Smj1kBlR9TYG4ZspUrzsaDNLJ3IFMGeDdblevMTE
# 执行批准命令

[root@k8s-master1 ~]# kubectl get pod -n kube-system
NAME                                     READY   STATUS     RESTARTS       AGE
calico-kube-controllers-8db96c76-46qtc   1/1     Running    0              19h
calico-node-fwb77                        1/1     Running    17 (15h ago)   10h
calico-node-tgncd                        1/1     Running    0              19h
calico-node-tz4z7                        0/1     Init:0/3   0              12s
# 查看状态,等待running

[root@k8s-master1 ~]# kubectl get node
NAME          STATUS   ROLES    AGE   VERSION
k8s-master1   Ready    <none>   44h   v1.23.8
k8s-node1     Ready    <none>   11h   v1.23.8
# 在执行上面的步骤,将node2节点加入集群中

11、部署Dashboard和coredns

1、部署coredns

# coredns是kubernetes的默认DNS服务器。是利用watch Kubernetes的Service和Pod生成NDS记录,然后通过配置kubelet的DNS选项让新启动的Pod使用CoreDNS提供的kubernetes集群内域名解析服务。
kubectl  apply -f coredns.yaml

kubectl get pod -n kube-system
NAME                                     READY   STATUS    RESTARTS            AGE
calico-kube-controllers-d4bfdcb9-fn5z5   1/1     Running   1 (5h8m ago)        18h
calico-node-c56rd                        1/1     Running   1 (<invalid> ago)   18h
calico-node-fjpgt                        1/1     Running   1 (5h8m ago)        18h
calico-node-xsf7r                        1/1     Running   1 (5h8m ago)        18h
coredns-7f9886848d-z4h5v                 1/1     Running   0                   90s

2、部署Dashboard

kubectl apply -f dashboard.yaml

kubectl create serviceaccount dashboard-admin -n kube-system

kubectl create clusterrolebinding dashboard-admin --clusterrole=cluster-admin --serviceaccount=kube-system:dashboard-admin

kubectl describe secrets -n kube-system $(kubectl -n kube-system get secret | awk '/dashboard-admin/{print $1}')
# 获取到下方的token,将获取到的token复制到Kubernetes 仪表盘中。
Name:         dashboard-admin-token-7n7xg
Namespace:    kube-system
Labels:       <none>
Annotations:  kubernetes.io/service-account.name: dashboard-admin
              kubernetes.io/service-account.uid: edccbcee-c8a1-4381-9db3-ce7d1483b3ed

Type:  kubernetes.io/service-account-token

Data
====
namespace:  11 bytes
token:      eyJhbGciOiJSUzI1NiIsImtpZCI6InZ3QTFnaEZKd0EzVU5tM0FNQ3UwTkJpYTZPSDhNd2Y3TXJmQU9IbzdMWGMifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tN243eGciLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiZWRjY2JjZWUtYzhhMS00MzgxLTlkYjMtY2U3ZDE0ODNiM2VkIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.vkYxjwfsND9ExjaGFFx4k7okOFkObfEame3m3faY0sP2j3n-inH9yBaFeftNZ32OUm-icwm_Nh9DxIsvXYwKH_mrIU1TcJn_v7PnCvvRmyNt4vKuIpUlRsMZchCI7PuDcQqqZkfvHGIpEO43QKWC7H0wR00hmRUJwfXaRYVEc-TZFRuwVdHhsiA2or52xl0qwFgzPRdtqRmsHgTtX4ZjgQ2uBmauLveJfCvEpw63NHeYDYFvbQyDkG0Qj1ENf9N_Ie5YBXOxgStWVEprwK_HEjjlMWhGDBTb3FK48h3wbWP2tbFkthTlJ6hLCKDPNd6No1dS7Llacv3AOH6kWJdZTA
ca.crt:     1363 bytes

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐