部署Kubernetes高可用集群(v1.22,二进制)

一. 系统软件环境

软件 版本
操作系统 CentOS Linux release 7.8.2003 (Core)
Docker docker-20.10.8-ce
Kubernetes 1.22.1
ETCD etcd-v3.5.0
Calico v3.20
Coredns 1.8.4
Dashboard v2.3.1
Ingress-nginx v1.0.0

节点组件

角色 IP 组件
k8s-master 172.16.20.50 kube-apiserver, kube-controller-manager, kube-scheduler, docker, kubelet, kube-proxy,etcd
k8s-node1 172.16.20.51 docker, kubelet, kube-proxy, etcd
k8s-node2 172.16.20.52 docker, kubelet, kube-proxy, etcd

二. 基础环境配置

所有Master,NODE节点

创建目录

## 创建目录结构
mkdir -pv /opt/etcd/{bin,cfg,ssl}
mkdir -pv /opt/k8s/{bin,cfg,ssl,logs,yaml}
mkdir -pv /data/TLS/{etcd,k8s}

hosts配置

cat >> /etc/hosts << EOF
172.16.20.50 k8s-master
172.16.20.51 k8s-node1
172.16.20.52 k8s-node2
172.16.20.50 etcd-1
172.16.20.51 etcd-2
172.16.20.52 etcd-3
EOF

## 主机名修改

在对应节点分别执行

hostnamectl set-hostname k8s-master
hostnamectl set-hostname k8s-node1
hostnamectl set-hostname k8s-node2

其他系统设置

## 启用IPVS模式相关配置
cat > /etc/sysctl.d/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
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
## 生效
sysctl --system

关闭swap

## 临时关闭:
swapoff -a

## 永久关闭
sed -ri 's/.*swap.*/#&/' /etc/fstab

配置IPVS模式所需模块

安装ipvs ipset

yum -y install ipvsadm  ipset conntrack-tools

配置系统加载模块

cat > /etc/modules-load.d/ipvs.conf <

查看生效模块

lsmod |grep ip_vs

limit配置

vim /etc/security/limits.conf
//加入
* soft nofile 655360
* hard nofile 655360
 
* soft nproc 655650
* hard nproc 655650

其他系统配置

## 时间同步
/usr/bin/cp -f /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
ntpdate time.windows.com

## 为了便捷操作,在k8s-master上创建免密登录其他节点
ssh-keygen -t rsa
ssh-copy-id -i /root/.ssh/id_rsa.pub root@k8s-node1
ssh-copy-id -i /root/.ssh/id_rsa.pub root@k8s-node2

##配置环境变量(根据节点情况,一般配置master节点即可)
echo 'export PATH=$PATH:/opt/k8s/bin/' >> /etc/profile
echo 'export PATH=$PATH:/opt/etcd/bin/' >> /etc/profile
source /etc/profile

三. 安装cfssl证书工具

master节点

## 创建自签证书目录
mkdir -pv /data/TLS/{etcd,k8s}

## 下载地址
https://github.com/cloudflare/cfssl/releases/download

## 移动到/usr/bin目录下
mv cfssl_linux-amd64 /usr/bin/cfssl
mv cfssl-certinfo_linux-amd64 /usr/bin/cfssl-certinfo
mv cfssljson_linux-amd64 /usr/bin/cfssljson

## 添加可执行权限
chmod +x /usr/bin/cfssl*

## 生成配置模版命令
cfssl print-defaults config > config.json
cfssl print-defaults csr > csr.json

四. 部署ETCD集群

操作节点: master

节点名称 IP
etcd-1 172.16.20.50
etcd-2 172.16.20.51
etcd-3 172.16.20.52

4.1 自签TLS证书

  • ETCD-1操作,然后同步到其他节点

自签证书颁发机构(CA)

cd /data/TLS/etcd/

自签CA

cd /data/TLS/etcd/
cat > ca-config.json << EOF
{
  "signing": {
    "default": {
      "expiry": "87600h"
    },
    "profiles": {
      "etcd": {
         "expiry": "87600h",
         "usages": [
            "signing",
            "key encipherment",
            "server auth",
            "client auth"
        ]
      }
    }
  }
}
EOF
cat > ca-csr.json << EOF
{
    "CN": "etcd CA",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "L": "Beijing",
            "ST": "Beijing"
        }
    ]
}
EOF

生成ca证书

cfssl gencert -initca ca-csr.json | cfssljson -bare ca
ls
ca-config.json  ca.csr  ca-csr.json  ca-key.pem  ca.pem

使用自签CA签发Etcd HTTPS证书

创建证书申请文件(hosts中要包含所有etcd节点ip,也可以多写几个预留)

cat > server-csr.json << EOF
{
    "CN": "etcd",
    "hosts": [
    "172.16.20.50",
    "172.16.20.51",
    "172.16.20.52",
    "172.16.20.55"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "L": "BeiJing",
            "ST": "BeiJing"
        }
    ]
}
EOF

生成server证书

cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=etcd server-csr.json | cfssljson -bare server

ls
ca-config.json  ca-key.pem  server-csr.json
ca.csr          ca.pem      server-key.pem
ca-csr.json     server.csr  server.pem

## 证书拷贝到etcd目录下
rsync -av /data/TLS/etcd/*.pem /opt/etcd/ssl/
ls /opt/etcd/ssl/
ca-key.pem  ca.pem  server-key.pem  server.pem

4.2 ETCD安装

下载地址

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

解压部署

  • ETCD-1操作,然后同步到其他节点
tar -zxf etcd-v3.5.0-linux-amd64.tar.gz
mv etcd-v3.5.0-linux-amd64/etcd* /opt/etcd/bin/

4.3 创建ETCD配置文件

ETCD各节点配置基本相同, 注意修改如下配置, 修改成本机etcd-name或者IP

cat > /opt/etcd/cfg/etcd.conf << EOF
#[Member]
ETCD_NAME="etcd-1"
ETCD_DATA_DIR="/var/lib/etcd/default.etcd"
ETCD_LISTEN_PEER_URLS="https://172.16.20.50:2380"
ETCD_LISTEN_CLIENT_URLS="https://172.16.20.50:2379"

#[Clustering]
ETCD_INITIAL_ADVERTISE_PEER_URLS="https://172.16.20.50:2380"
ETCD_ADVERTISE_CLIENT_URLS="https://172.16.20.50:2379"
ETCD_INITIAL_CLUSTER="etcd-1=https://172.16.20.50:2380,etcd-2=https://172.16.20.51:2380,etcd-3=https://172.16.20.52:2380"
ETCD_INITIAL_CLUSTER_TOKEN="etcd-cluster"
ETCD_INITIAL_CLUSTER_STATE="new"
EOF
  • 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:集群节点地址
  • ETCD_INITIAL_CLUSTER_TOKEN:集群Token
  • ETCD_INITIAL_CLUSTER_STATE:加入集群的当前状态,new是新集群,existing表示加入已有集群

4.4 创建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=/opt/etcd/cfg/etcd.conf
ExecStart=/opt/etcd/bin/etcd \
--cert-file=/opt/etcd/ssl/server.pem \
--key-file=/opt/etcd/ssl/server-key.pem \
--peer-cert-file=/opt/etcd/ssl/server.pem \
--peer-key-file=/opt/etcd/ssl/server-key.pem \
--trusted-ca-file=/opt/etcd/ssl/ca.pem \
--peer-trusted-ca-file=/opt/etcd/ssl/ca.pem \
--logger=zap
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

4.5 同步ETCD到其余节点

## 同步ETCD目录
rsync -av /opt/etcd etcd-2:/opt/
rsync -av /opt/etcd etcd-3:/opt/
## 同步ETCD启动配置文件
rsync -av /usr/lib/systemd/system/etcd.service etcd-2:/usr/lib/systemd/system/etcd.service
rsync -av /usr/lib/systemd/system/etcd.service etcd-3:/usr/lib/systemd/system/etcd.service

同步ETCD目录后, 各节点修改etcd.conf, 修改对应的节点名称和节点IP

4.6 启动ETCD

## 重载启动配置文件
systemctl daemon-reload
## 启动etcd
systemctl restart etcd
## 加入开机自启动
systemctl enable etcd

## 4.7 验证ETCD状态

/opt/etcd/bin/etcdctl --cacert=/opt/etcd/ssl/ca.pem --cert=/opt/etcd/ssl/server.pem --key=/opt/etcd/ssl/server-key.pem --endpoints="https://172.16.20.50:2379,https://172.16.20.51:2379,https://172.16.20.52:2379" endpoint health

/opt/etcd/bin/etcdctl --cacert=/opt/etcd/ssl/ca.pem --cert=/opt/etcd/ssl/server.pem --key=/opt/etcd/ssl/server-key.pem --endpoints="https://172.16.20.50:2379,https://172.16.20.51:2379,https://172.16.20.52:2379" member list

五. 部署DOCKER

二进制方式

操作节点: master

5.1 下载地址

https://download.docker.com/linux/static/stable/x86_64/

tar zxf docker-20.10.8.tgz
rsync -av docker/* /usr/bin/
## 同步到节点
rsync -av docker/* k8s-node1:/usr/bin/
rsync -av docker/* k8s-node2:/usr/bin/

编辑docker配置文件

mkdir /etc/docker
cat > /etc/docker/daemon.json << EOF
{
"registry-mirrors": ["https://gsm39obv.mirror.aliyuncs.com"]
}
EOF
## 同步到节点
rsync -av /etc/docker k8s-node1:/etc/
rsync -av /etc/docker k8s-node2:/etc/

5.2 创建systemd启动文件

cat > /usr/lib/systemd/system/docker.service << EOF
[Unit]
Description=Docker Application Container Engine
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 $MAINPID
LimitNOFILE=infinity
LimitNPROC=infinity
TimeoutStartSec=0
Delegate=yes
KillMode=process
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s

[Install]
WantedBy=multi-user.target
EOF
## 同步到节点
rsync -av /usr/lib/systemd/system/docker.service k8s-node1:/usr/lib/systemd/system/docker.service
rsync -av /usr/lib/systemd/system/docker.service k8s-node2:/usr/lib/systemd/system/docker.service

5.3 启动docker

systemctl daemon-reload
systemctl restart docker
systemctl enable docker

## 验证docker启动状态
docker info

六. kubenetes部署

二进制文件部署

下载地址

https://dl.k8s.io/v1.22.1/kubernetes-server-linux-amd64.tar.gz

解压

tar zxf kubernetes-server-linux-amd64.tar.gz
cd kubernetes/server/bin

拷贝配置到节点

## master节点
rsync -av kubectl kube-apiserver kube-controller-manager kube-scheduler kubelet kube-proxy /opt/k8s/bin/
## node节点
rsync -av kubelet kube-proxy root@k8s-node1:/opt/k8s/bin/
rsync -av kubelet kube-proxy root@k8s-node2:/opt/k8s/bin/

七. Master节点部署

操作节点: master

7.1 部署kube-apiserver

生成kube-apiserver证书

  1. 自签证书颁发机构(CA)
cd /data/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": "Beijing",
            "ST": "Beijing",
            "O": "k8s",
            "OU": "System"
        }
    ]
}
EOF

生成CA证书

cfssl gencert -initca ca-csr.json | cfssljson -bare ca
  1. 使用自签CA签发kube-apiserver HTTPS证书
## 创建证书申请文件:
cat > server-csr.json << EOF
{
    "CN": "kubernetes",
    "hosts": [
      "10.0.0.1",
      "127.0.0.1",
      "172.16.20.50",
      "172.16.20.51",
      "172.16.20.52",
      "172.16.20.55",
      "kubernetes",
      "kubernetes.default",
      "kubernetes.default.svc",
      "kubernetes.default.svc.cluster",
      "kubernetes.default.svc.cluster.local"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "L": "BeiJing",
            "ST": "BeiJing",
            "O": "k8s",
            "OU": "System"
        }
    ]
}
EOF

注:上述文件hosts字段中IP为所有Master/LB/VIP IP,一个都不能少!为了方便后期扩容可以多写几个预留的IP。

生成证书

cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes server-csr.json | cfssljson -bare server

同步证书

# master 节点
rsync -av /data/TLS/k8s/ca*pem /opt/k8s/ssl/
rsync -av /data/TLS/k8s/server*pem /opt/k8s/ssl/

# 同步至node节点
rsync -av /data/TLS/k8s/ca.pem root@k8s-node1:/opt/k8s/ssl
rsync -av /data/TLS/k8s/ca.pem root@k8s-node2:/opt/k8s/ssl

创建conf配置文件

cat > /opt/k8s/cfg/kube-apiserver.conf << EOF
KUBE_APISERVER_OPTS="--logtostderr=false \\
--feature-gates=RemoveSelfLink=false \\
--v=2 \\
--log-dir=/opt/k8s/logs \\
--bind-address=172.16.20.50 \\
--secure-port=6443 \\
--advertise-address=172.16.20.50 \\
--anonymous-auth=false \\
--allow-privileged=true \\
--runtime-config=api/all=true \\
--service-cluster-ip-range=10.0.0.0/24 \\
--enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,ResourceQuota,NodeRestriction,DefaultStorageClass \\
--authorization-mode=RBAC,Node \\
--enable-bootstrap-token-auth \\
--token-auth-file=/opt/k8s/cfg/token.csv \\
--service-node-port-range=30000-32767 \\
--kubelet-client-certificate=/opt/k8s/ssl/server.pem \\
--kubelet-client-key=/opt/k8s/ssl/server-key.pem \\
--tls-cert-file=/opt/k8s/ssl/server.pem  \\
--tls-private-key-file=/opt/k8s/ssl/server-key.pem \\
--client-ca-file=/opt/k8s/ssl/ca.pem \\
--apiserver-count=1 \\
--service-account-issuer=https://kubernetes.default.svc.cluster.local \\
--service-account-key-file=/opt/k8s/ssl/ca-key.pem \\
--service-account-signing-key-file=/opt/k8s/ssl/server-key.pem \\
#--service-account-signing-key-file=/etc/kubernetes/ssl/ca-key.pem \\
--etcd-servers=https://172.16.20.50:2379,https://172.16.20.51:2379,https://172.16.20.52:2379 \\
--etcd-cafile=/opt/etcd/ssl/ca.pem \\
--etcd-certfile=/opt/etcd/ssl/server.pem \\
--etcd-keyfile=/opt/etcd/ssl/server-key.pem \\
--requestheader-client-ca-file=/opt/k8s/ssl/ca.pem \\
--proxy-client-cert-file=/opt/k8s/ssl/server.pem \\
--proxy-client-key-file=/opt/k8s/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 \\
--event-ttl=1h \\
--audit-log-path=/opt/k8s/logs/k8s-audit.log"
EOF

api-server参数详解: https://kubernetes.io/zh/docs/reference/command-line-tools-reference/kube-apiserver/

创建TLS机制所需TOKEN

  • TLS Bootstraping:Master apiserver启用TLS认证后,Node节点kubelet和kube-proxy要与kube-apiserver进行通信,必须使用CA签发的有效证书才可以,当Node节点很多时,这种客户端证书颁发需要大量工作,同样也会增加集群扩展复杂度。为了简化流程,Kubernetes引入了TLS bootstraping机制来自动颁发客户端证书,kubelet会以一个低权限用户自动向apiserver申请证书,kubelet的证书由apiserver动态签署。所以强烈建议在Node上使用这种方式,目前主要用于kubelet,kube-proxy还是由我们统一颁发一个证书。
## 创建kube-apiserver.conf中所需的token.csv
echo "`head -c 16 /dev/urandom | od -An -t x | tr -d ' '`,kubelet-bootstrap,10001,\"system:bootstrappers\"" > /opt/k8s/cfg/token.csv

创建systemd启动文件

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

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

[Install]
WantedBy=multi-user.target
EOF

启动apiserver

systemctl daemon-reload
systemctl restart kube-apiserver
systemctl enable kube-apiserver

7.2 部署kube-controller-manager

创建conf配置文件

cat > /opt/k8s/cfg/kube-controller-manager.conf << EOF
KUBE_CONTROLLER_MANAGER_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/k8s/logs \\
--leader-elect=true \\
--kubeconfig=/opt/k8s/cfg/kube-controller-manager.kubeconfig \\
--bind-address=127.0.0.1 \\
--allocate-node-cidrs=true \\
--cluster-cidr=10.244.0.0/16 \\
--service-cluster-ip-range=10.0.0.0/24 \\
--cluster-signing-cert-file=/opt/k8s/ssl/ca.pem \\
--cluster-signing-key-file=/opt/k8s/ssl/ca-key.pem  \\
--root-ca-file=/opt/k8s/ssl/ca.pem \\
--service-account-private-key-file=/opt/k8s/ssl/ca-key.pem \\
--cluster-signing-duration=87600h0m0s"
EOF
  • –kubeconfig:连接apiserver配置文件
  • –leader-elect:当该组件启动多个时,自动选举(HA)
  • –cluster-signing-cert-file/–cluster-signing-key-file:自动为kubelet颁发证书的CA,与apiserver保持一致

生成kubeconfig配置文件

生成证书

kube-controller-manager.kubeconfig

cd /data/TLS/k8s

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

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

生成kubeconfig文件(在/data/TLS/k8s下执行)

KUBE_CONFIG="/opt/k8s/cfg/kube-controller-manager.kubeconfig"
KUBE_APISERVER="https://172.16.20.50:6443"

kubectl config set-cluster kubernetes \
  --certificate-authority=/opt/k8s/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}

创建systemd启动文件

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

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

[Install]
WantedBy=multi-user.target
EOF

启动kube-controller-manager

systemctl daemon-reload
systemctl restart kube-controller-manager
systemctl enable kube-controller-manager

7.3 部署kube-scheduler

创建conf配置文件

cat > /opt/k8s/cfg/kube-scheduler.conf << EOF
KUBE_SCHEDULER_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/k8s/logs \\
--leader-elect \\
--kubeconfig=/opt/k8s/cfg/kube-scheduler.kubeconfig \\
--bind-address=127.0.0.1"
EOF
  • –kubeconfig:连接apiserver配置文件
  • –leader-elect:当该组件启动多个时,自动选举(HA)

生成kubeconfig配置文件

kube-scheduler.kubeconfig

cd /data/TLS/k8s

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

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

生成kubeconfig文件(在/data/TLS/k8s下执行)

KUBE_CONFIG="/opt/k8s/cfg/kube-scheduler.kubeconfig"
KUBE_APISERVER="https://172.16.20.50:6443"

kubectl config set-cluster kubernetes \
  --certificate-authority=/opt/k8s/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}

创建systemd启动文件

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

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

[Install]
WantedBy=multi-user.target
EOF

启动kube-scheduler

systemctl daemon-reload
systemctl restart kube-scheduler
systemctl enable kube-scheduler

7.4 查看集群状态

生成kubectl连接集群的证书

cd /data/TLS/k8s

cat > admin-csr.json <

生成kubeconfig配置文件

mkdir -pv /root/.kube
KUBE_CONFIG="/root/.kube/config"
KUBE_APISERVER="https://172.16.20.50:6443"

kubectl config set-cluster kubernetes \
  --certificate-authority=/opt/k8s/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  get cs
Warning: v1 ComponentStatus is deprecated in v1.19+
NAME                 STATUS    MESSAGE                         ERROR
scheduler            Healthy   ok
controller-manager   Healthy   ok
etcd-1               Healthy   {"health":"true","reason":""}
etcd-2               Healthy   {"health":"true","reason":""}
etcd-0               Healthy   {"health":"true","reason":""}

八. NODE节点部署

  • master上执行

master也需要部署node节点相应组件: kubelet和kube-proxy

8.1 部署kubelet

创建conf配置文件

cat > /opt/k8s/cfg/kubelet.conf << EOF
KUBELET_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/k8s/logs \\
--hostname-override=k8s-master \\
--network-plugin=cni \\
--kubeconfig=/opt/k8s/cfg/kubelet.kubeconfig \\
--bootstrap-kubeconfig=/opt/k8s/cfg/bootstrap.kubeconfig \\
--config=/opt/k8s/cfg/kubelet-config.yml \\
--cert-dir=/opt/k8s/ssl \\
--pod-infra-container-image=registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.5"
EOF
  • –hostname-override:显示名称,为节点hostname, 集群中唯一
  • –network-plugin:启用CNI
  • –kubeconfig:空路径,会自动生成,后面用于连接apiserver
  • –bootstrap-kubeconfig:首次启动向apiserver申请证书
  • –config:配置参数文件
  • –cert-dir:kubelet证书生成目录
  • –pod-infra-container-image:管理Pod网络容器的镜像

创建yml参数配置文件

kubelet-config.yml文件内容

cat > /opt/k8s/cfg/kubelet-config.yml << EOF
kind: KubeletConfiguration
apiVersion: kubelet.config.k8s.io/v1beta1
address: 0.0.0.0
port: 10250
readOnlyPort: 10255
cgroupDriver: cgroupfs
clusterDNS:
- 10.0.0.2
clusterDomain: cluster.local 
failSwapOn: false
authentication:
  anonymous:
    enabled: false
  webhook:
    cacheTTL: 2m0s
    enabled: true
  x509:
    clientCAFile: /opt/k8s/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

创建bootstrap.kubeconfig配置文件

  • kubelet初次加入集群引导kubeconfig文件

master节点操作

KUBE_CONFIG="/opt/k8s/cfg/bootstrap.kubeconfig"
KUBE_APISERVER="https://172.16.20.50:6443"
TOKEN=`cat /opt/k8s/cfg/token.csv|awk -F',' '{print $1}'` # 与token.csv里保持一致

# 生成 kubelet bootstrap kubeconfig 配置文件
kubectl config set-cluster kubernetes \
  --certificate-authority=/opt/k8s/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}

创建systemd启动文件

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

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

[Install]
WantedBy=multi-user.target
EOF

启动kubelet

systemctl daemon-reload
systemctl restart kubelet
systemctl enable kubelet

同步kubelet配置到其余节点

同步kubelet.conf, kubelet-config.yml, bootstrap.kubeconfig, kubelet.service到所有节点, 修改kubelet.conf中hostname-override参数为对应节点的hostname

## 同步kubelet配置
rsync -av /opt/k8s/cfg/{kubelet.conf,kubelet-config.yml,bootstrap.kubeconfig} root@k8s-node1:/opt/k8s/cfg/
rsync -av /opt/k8s/cfg/{kubelet.conf,kubelet-config.yml,bootstrap.kubeconfig} root@k8s-node2:/opt/k8s/cfg/


## 同步启动文件
rsync -av /usr/lib/systemd/system/kubelet.service root@k8s-node1:/usr/lib/systemd/system/kubelet.service
rsync -av /usr/lib/systemd/system/kubelet.service root@k8s-node2:/usr/lib/systemd/system/kubelet.service

## 其余节点启动kubelet
systemctl daemon-reload
systemctl restart kubelet
systemctl enable kubelet

kubelet-bootstrap授权

到这里, 启动kubelet时候会报错

failed to run Kubelet: cannot create certificate signing request: certificatesigningrequests.certificates.k8s.io is forbidden: User "kubelet-bootstrap" cannot create resource "certificatesigningrequests" in API group "certificates.k8s.io" at the cluster scope

这是因为kubelet-bootstrap没有权限申请证书,在master上查看证书申请列表也是空的

kubectl get csr
No resources found in default namespace.

这时候需要在master上操作,授权kubelet-bootstrap用户允许请求证书

cat > /opt/k8s/yaml/kubelet-bootstrap-rbac.yaml << EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: create-csrs-for-bootstrapping
subjects:
- kind: Group
  name: system:bootstrappers
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: system:node-bootstrapper
  apiGroup: rbac.authorization.k8s.io  
EOF

kubectl apply -f /opt/k8s/yaml/kubelet-bootstrap-rbac.yaml

重新启动kubelet,然后在master上查看证书申请

kubectl get csr
NAME 					AGE   				SIGNERNAME 				REQUESTOR 				CONDITION
node-csr-dqVIp0rPbtw3PNeY25Z0V27I2wxANX8R29yjdXT9Q34   36s   kubernetes.io/kube-apiserver-client-kubelet   kubelet-bootstrap   Pending

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

for csr in `kubectl get csr |awk 'NR>1 {print $1}'`;do kubectl certificate approve $csr;done

再次查看证书申请

kubectl get csr
NAME 						AGE    					SIGNERNAME 				REQUESTOR           CONDITION
node-csr-dqVIp0rPbtw3PNeY25Z0V27I2wxANX8R29yjdXT9Q34   2m9s   kubernetes.io/kube-apiserver-client-kubelet   kubelet-bootstrap   Approved,Issued

查看节点状态

# kubectl get node
NAME          STATUS     ROLES    AGE   VERSION
k8s-master   NotReady      30s   v1.22.1
k8s-node1     NotReady      39s   v1.22.1
k8s-node2     NotReady      48s   v1.22.1

注:由于CNI网络插件还没有部署,节点会没有准备就绪 NotReady

8.2 部署kube-proxy

创建conf配置文件

cat > /opt/k8s/cfg/kube-proxy.conf << EOF
KUBE_PROXY_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/k8s/logs \\
--config=/opt/k8s/cfg/kube-proxy-config.yml"
EOF

创建yml参数配置文件–IPVS模式

修改kube-proxy-config.yml

cat > /opt/k8s/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
iptables:
  masqueradeAll: true
  masqueradeBit: null
  minSyncPeriod: 0s
  syncPeriod: 0s
ipvs:
  masqueradeAll: true
  excludeCIDRs: null
  minSyncPeriod: 0s
  scheduler: "rr"
  strictARP: false
  syncPeriod: 0s
  tcpFinTimeout: 0s
  tcpTimeout: 0s
  udpTimeout: 0s
mode: "ipvs"
clientConnection:
  kubeconfig: /opt/k8s/cfg/kube-proxy.kubeconfig
hostnameOverride: k8s-master
clusterCIDR: 10.0.0.0/24
EOF

注意:

修改hostnameOverride为节点hostname

clusterCIDR: kube-proxy 根据 --cluster-cidr 判断集群内部和外部流量,指定 --cluster-cidr 或 --masquerade-all 选项后 kube-proxy 才会对访问 Service IP 的请求做 SNAT

clusterCIDR: 10.0.0.0/24这个是集群service段,和kube-apiserver.conf还有kube-controller-manager.conf中--service-cluster-ip-range=10.0.0.0/24参数保持一致

生成kube-proxy.kubeconfig文件

master节点操作

生成kube-proxy证书:

cd /data/TLS/k8s

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

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

生成kube-proxy.kubeconfig文件

KUBE_CONFIG="/opt/k8s/cfg/kube-proxy.kubeconfig"
KUBE_APISERVER="https://172.16.20.50:6443"

kubectl config set-cluster kubernetes \
  --certificate-authority=/opt/k8s/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}

创建systemd启动文件

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

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

[Install]
WantedBy=multi-user.target
EOF

启动kube-proxy

systemctl daemon-reload
systemctl restart kube-proxy
systemctl enable kube-proxy

验证IPVS模式

## 验证
ipvsadm -l

同步kube-proxy配置到其余节点

同步kube-proxy.conf, kube-proxy-config.yml, kube-proxy.kubeconfig, kube-proxy.service到所有节点, 修改kube-proxy-config.yml配置文件中hostnameOverride参数为对应节点的hostname

## 同步kube-proxy配置
rsync -av /opt/k8s/cfg/{kube-proxy.conf,kube-proxy-config.yml,kube-proxy.kubeconfig} root@k8s-node1:/opt/k8s/cfg/
rsync -av /opt/k8s/cfg/{kube-proxy.conf,kube-proxy-config.yml,kube-proxy.kubeconfig} root@k8s-node2:/opt/k8s/cfg/

## 同步启动文件
rsync -av /usr/lib/systemd/system/kube-proxy.service root@k8s-node1:/usr/lib/systemd/system/kube-proxy.service
rsync -av /usr/lib/systemd/system/kube-proxy.service root@k8s-node2:/usr/lib/systemd/system/kube-proxy.service

## 其余节点启动kubelet
systemctl daemon-reload
systemctl restart kube-proxy
systemctl enable kube-proxy

九. 授权apiserver访问kubelet

  • 如果不进行授权, 将无法管理容器
cat > /opt/k8s/yaml/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

十. 部署相关插件

为master节点打污点, master节点不运行pod

kubectl taint nodes k8s-master node-role.kubernetes.io/master=:NoSchedule

master节点操作

10.1 部署cni网络-Calico

下载地址

https://docs.projectcalico.org/getting-started/kubernetes/installation/config-options

curl -k https://docs.projectcalico.org/manifests/calico-etcd.yaml -o calico-etcd.yaml

配置Secret

apiVersion: v1
kind: Secret
type: Opaque
metadata:
  name: calico-etcd-secrets
  namespace: kube-system
data:
  # Populate the following with etcd TLS configuration if desired, but leave blank if
  # not using TLS for etcd.
  # The keys below should be uncommented and the values populated with the base64
  # encoded contents of each file that would be associated with the TLS data.
  # Example command for encoding a file contents: cat  | base64 -w 0
  etcd-key: -key.pem转换内容>
  etcd-cert: >
  etcd-ca: >
转换命令:
cat  | base64 -w 0| tr -d '\n'

配置ConfigMap

kind: ConfigMap
apiVersion: v1
metadata:
  name: calico-config
  namespace: kube-system
data:
  # Configure this with the location of your etcd cluster.
  etcd_endpoints: "https://172.16.20.50:2379,https://172.16.20.51:2379,https://172.16.20.52:2379"
  # If you're using TLS enabled etcd uncomment the following.
  # You must also populate the Secret below with these files.
  etcd_ca: "/calico-secrets/etcd-ca"
  etcd_cert: "/calico-secrets/etcd-cert"
  etcd_key: "/calico-secrets/etcd-key"
  # Typha is disabled.
  typha_service_name: "none"
  # Configure the backend to use.
  calico_backend: "bird"

etcd_endpoints: ETCD地址

修改Pod CIDR

查找关键字CALICO_IPV4POOL_CIDR; Pod CIDR要与控制器配置文件kube-controller-manager.conf中配置的对应,10.244.0.0/16

# The default IPv4 pool to create on startup if none exists. Pod IPs will be
# chosen from this range. Changing this value after installation will have
# no effect. This should fall within `--cluster-cidr`.
- name: CALICO_IPV4POOL_CIDR
  value: "10.244.0.0/16"

配置calico工作模式

  • 默认IPIP模式,如果关闭后,模式就变为BGP模式
# Enable IPIP
- name: CALICO_IPV4POOL_IPIP
  value: "Always"

指定网卡

修改DaemonSet控制器下的containers.env
加入
# Specify interface
- name: IP_AUTODETECTION_METHOD
  value: "interface=ens192"

ens.*根据实际环境修改

部署calico网络

##先修改policy/v1beta1为policy/v1
kubectl apply -f calico-etcd.yaml

部署calico管理工具

下载

wget -O /usr/bin/calicoctl https://github.com/projectcalico/calicoctl/releases/download/v3.18.1/calicoctl
chmod +x /usr/bin/calicoctl

calicoctl配置文件

mkdir -pv /etc/calico/
cat > /etc/calico/calicoctl.cfg << EOF
apiVersion: projectcalico.org/v3
kind: CalicoAPIConfig
metadata:
spec:
  datastoreType: "etcdv3"
  etcdEndpoints: "https://3.1.101.49:2379,https://3.1.101.50:2379,https://3.1.101.51:2379,https://3.1.101.52:2379,https://3.1.101.53:2379"
  etcdKeyFile: "/opt/etcd/ssl/server-key.pem"
  etcdCertFile: "/opt/etcd/ssl/server.pem"
  etcdCACertFile: "/opt/etcd/ssl/ca.pem"
EOF

calicoctl常用命令

calicoctl node status			//查看当前网络状态,不需要指定配置文件
calicoctl get nodes -o wide			//查看节点,需要指定配置文件
calicoctl get ippool -o wide	//查看 IPAM的IP地址池

10.2 部署Dashboard面板

下载yaml文件

curl https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/recommended.yaml -o kubernetes-dashboard.yaml

替换镜像地址(二选一)

  1. 更换docker官方镜像更换为阿里云镜像地址(下载更快)
sed -i 's#kubernetesui#registry.cn-hangzhou.aliyuncs.com\/google_containers#g' kubernetes-dashboard.yaml
  1. 者将两个image地址更换为docker镜像仓库最新版本地址
kubernetesui/dashboard:v2.3.1
kubernetesui/metrics-scraper:v1.0.7

配置dashboard-service

默认Dashboard只能集群内部访问,修改Service为NodePort类型,暴露到外部(kubernetes-dashboard部分), 如下:

cat >> kubernetes-dashboard.yaml << EOF
---
# ------------------- dashboard-service ------------------- #
kind: Service
apiVersion: v1
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kubernetes-dashboard
spec:
  ports:
    - port: 443
      targetPort: 8443
      nodePort: 30001
  type: NodePort
  selector:
    k8s-app: kubernetes-dashboard
EOF

配置dashboard-admin帐号

cat >> kubernetes-dashboard.yaml << EOF
---
# ------------------- dashboard-admin ------------------- #
apiVersion: v1
kind: ServiceAccount
metadata:
  name: dashboard-admin
  namespace: kubernetes-dashboard

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: dashboard-admin
subjects:
- kind: ServiceAccount
  name: dashboard-admin
  namespace: kubernetes-dashboard
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
EOF

部署kubernetes-dashboard

## 部署
kubectl apply -f kubernetes-dashboard.yaml

## 查看部署状态
kubectl get all -n kubernetes-dashboard -o wide

## 获取令牌
kubectl describe secrets -n kubernetes-dashboard dashboard-admin

## 访问
https://NODE_IP:30001

部署提示:

Warning: spec.template.metadata.annotations[seccomp.security.alpha.kubernetes.io/pod]: deprecated since v1.19; use the "seccompProfile" field instead

解决方法:

将seccomp.security.alpha.kubernetes.io/pod替换为seccompProfile, 重新执行即可

10.3 部署coredns

下载yaml配置文件

  • 当前版本镜像为coredns:1.8.4

https://github.com/coredns/deployment/blob/master/kubernetes/coredns.yaml.sed

下载coredns.yaml.sed,修改后保存为coredns.yaml

修改yaml配置文件

62行左右   kubernetes cluster.local {  	-->大写部分修改成自己的域  一般为 cluster.local
66行左右	UPSTREAMNAMESERVER替换成/etc/resolv.conf
73行左右	删除STUBDOMAINS
200行左右	clusterIP: 10.0.0.2				--> clusterIP 修改成kubelet-config.yml中设置的clusterDNS地址

部署coredns

## 部署
kubectl apply -f coredns.yaml

## 验证
kubectl get pod -n kube-system

## 测试
kubectl run busybox --image=busybox --command -- ping www.baidu.com
kubectl exec -it pod/busybox -- /bin/sh -il
或者直接
kubectl run -it --image=busybox:1.28.4 --rm test /bin/sh
------------------------------------------------------------------------------
nslookup kubernetes
Server:    10.0.0.2
Address 1: 10.0.0.2

Name:      kubernetes
Address 1: 10.0.0.1
/ # nslookup www.baidu.com
Server:    10.0.0.2
Address 1: 10.0.0.2

Name:      www.baidu.com
Address 1: 220.181.38.150
Address 2: 220.181.38.149
------------------------------------------------------------------------------
执行ping命令
ping www.baidu.com
PING www.baidu.com (220.181.38.150): 56 data bytes
64 bytes from 220.181.38.150: seq=0 ttl=52 time=19.770 ms
64 bytes from 220.181.38.150: seq=1 ttl=52 time=19.765 ms

10.4 部署Ingress

ingress-nginx v1.0 最新版本 v1.0
适用于 Kubernetes 版本 v1.19+ (包括 v1.19
Kubernetes-v1.22+ 需要使用 ingress-nginx>=1.0,因为 networking.k8s.io/v1beta 已经移除

下载yaml配置文件

https://github.com/kubernetes/ingress-nginx/blob/controller-v1.0.0/deploy/static/provider/baremetal/deploy.yaml

内容保存为nginx-ingress-controller.yaml

修改ingress-nginx.yaml配置文件

替换镜像

  • 镜像是网上随便找的
sed -i "s#\(image: \)k8s.gcr.io/ingress-nginx/controller:.*#\1willdockerhub/ingress-nginx-controller:v1.0.0#g" nginx-ingress-controller.yaml

sed -i "s#\(image: \)k8s.gcr.io/ingress-nginx/kube-webhook-certgen:.*#\1hzde0128/kube-webhook-certgen:v1.0#g" nginx-ingress-controller.yaml

配置多副本(可选)

在Deployment控制器spec下加入replicas: 2

kind: Deployment
metadata:
  labels:
    helm.sh/chart: ingress-nginx-4.0.1
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/version: 1.0.0
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/component: controller
  name: ingress-nginx-controller
  namespace: ingress-nginx
spec:
  replicas: 2
  selector:

将ingress部署到指定节点(可选)

kubectl label nodes  k8s-node1 type=ingress
kubectl label nodes  k8s-node2 type=ingress

## 配置Deployment控制器下nodeSelector标签
      nodeSelector:
        kubernetes.io/os: linux
        type: "ingress"
      serviceAccountName: ingress-nginx
      terminationGracePeriodSeconds: 300

配置为hostNetwork模式(可选)

需要在Ingress Controller的yaml配置文件中指定使用主机网络hostNetwork: true位置位于Deployment.spec.tmplate.spec下

template:
    metadata:
      labels:
        app.kubernetes.io/name: ingress-nginx
        app.kubernetes.io/instance: ingress-nginx
        app.kubernetes.io/component: controller
    spec:
      hostNetwork: true
      dnsPolicy: ClusterFirst
  1. 配置hostNetwork模式就不需要配置Service了, 如果不配置hostNetwork在域名访问时候需要在域名后加上ingress的service端口
  2. 可以将控制器设置为DaemonSet,就可以将域名解析到任意节点进行访问了
  3. 部署ingress Controller节点端口(80,443)不能被占用

部署ingress-nginx

使用kubectl部署

kubectl apply -f nginx-ingress-controller.yaml

查看部署状态

kubectl get all -n ingress-nginx

验证ingress-nginx

  1. 创建deployment和service
cat > tomcat-deployment.yaml << EOF
apiVersion: apps/v1 
kind: Deployment   
metadata:             
  name: tomcat-app
  labels:       
    app: tomcat
spec:          
  replicas: 2 
  selector:
    matchLabels:
      app: tomcat
  template:        
    metadata:  
      labels:  
        app: tomcat
    spec:
      containers:     
      - name: tomcat-container
        image: tomcat:jre8-openjdk
        imagePullPolicy: Always          
        ports:
        - containerPort: 8080
        resources:
          requests:
            memory: "1Gi"
            cpu: "500m"
          limits: 
            memory: "2Gi" 
            cpu: "1000m"
---
apiVersion: v1
kind: Service
metadata:
  name: tomcat-service
  labels:
    app: tomcat
spec:
  selector:
    app: tomcat
  ports:
  - name: tomcat-port
    protocol: TCP
    port: 8080
    targetPort: 8080
  type: ClusterIP
EOF
  1. 配置nginx-ingress
cat > tomcat-ingress.yaml << EOF
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: tomcat
  namespace: default
  annotations:
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
  - host: tomcat.ing.cn
    http:
      paths:
      - path: "/"
        pathType: Prefix
        backend:
          service:
            name: tomcat-service
            port:
              number: 8080
EOF

查看ingress生效情况

# kubectl get ing
NAME     CLASS    HOSTS           ADDRESS                     PORTS   AGE
tomcat      tomcat.ing.cn   172.16.20.51,172.16.20.52   80      3m3s

本机配置hosts,通过域名访问,如果成功,说明ingress已生效

到此,k8s v1.22版本基础功能和插件,就部署完成了

你可能感兴趣的:(K8S,kubernetes,v1.22,k8s,二进制,calico网络)