使用 kubeadm 搭建 v1.19.3 版本 Kubernetes 集群

一、环境准备

1.1 实验环境

角色 IP地址 主机名 docker版本 硬件配置 系统 内核
master 10.0.0.130 k8s-master1 19.03.11 2C4G CentOS7.8 5.9.1-1.el7.elrepo.x86_64
node1 10.0.0.131 k8s-node1 19.03.11 2C4G CentOS7.8 5.9.1-1.el7.elrepo.x86_64
node2 10.0.0.132 k8s-node2 19.03.11 2C4G CentOS7.8 5.9.1-1.el7.elrepo.x86_64

1.2 每个节点配置host信息

cat >> /etc/hosts <<EOF
10.0.0.130 k8s-master1
10.0.0.131 k8s-node1
10.0.0.132 k8s-node2
EOF

1.3 禁用防火墙和selinux

# 禁用防火墙
systemctl stop firewalld && systemctl disable firewalld

# 禁用selinux
# 临时修改
setenforce 0

# 永久修改,重启服务器后生效
sed -i '7s/enforcing/disabled/' /etc/selinux/config

1.4 创建 /etc/sysctl.d/k8s.conf 文件,添加如下内容

# 向文件中写入以下内容
cat >/etc/sysctl.d/k8s.conf <<EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF

# 执行以下命令生效
modprobe br_netfilter && sysctl -p /etc/sysctl.d/k8s.conf

bridge-nf 说明

bridge-nf 使得 netfilter 可以对 Linux 网桥上的 IPv4/ARP/IPv6 包过滤。比如,设置 net.bridge.bridge-nf-call-iptables=1 后,二层的网桥在转发包时也会被 iptables的 FORWARD 规则所过滤。常用的选项包括:

  • net.bridge.bridge-nf-call-arptables:是否在 arptables 的 FORWARD 中过滤网桥的 ARP 包
  • net.bridge.bridge-nf-call-ip6tables:是否在 ip6tables 链中过滤 IPv6 包
  • net.bridge.bridge-nf-call-iptables:是否在 iptables 链中过滤 IPv4 包
  • net.bridge.bridge-nf-filter-vlan-tagged:是否在 iptables/arptables 中过滤打了 vlan 标签的包。

1.5 安装ipvs

脚本创建的/etc/sysconfig/modules/ipvs.modules文件,保证在节点重启后能自动加载所需模块。使用lsmod | grep -e ip_vs -e nf_conntrack_ipv4命令查看是否已经正确加载所需的内核模块

⚠️由于内核使用的是最新的版本5.9.1(发布日期2020.10.17),因此无法加载nf_conntrack_ipv4 模块 google到的答案 看这个isseu

# 向文件中写入以下内容
cat > /etc/sysconfig/modules/ipvs.modules <<EOF
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack
EOF

# 修改权限以及查看是否已经正确加载所需的内核模块
chmod 755 /etc/sysconfig/modules/ipvs.modules && bash /etc/sysconfig/modules/ipvs.modules && lsmod | grep -e ip_vs -e nf_conntrack_ipv4

ip_vs_sh               16384  0 
ip_vs_wrr              16384  0 
ip_vs_rr               16384  0 
ip_vs                 155648  6 ip_vs_rr,ip_vs_sh,ip_vs_wrr
nf_conntrack          155648  1 ip_vs
nf_defrag_ipv6         24576  2 nf_conntrack,ip_vs
libcrc32c              16384  3 nf_conntrack,xfs,ip_vs

安装ipset和ipvsadm(便于查看 ipvs 的代理规则)

yum -y install ipset ipvsadm

1.6 同步服务器时间

master节点操作

# 安装chrony
yum -y install chrony

# 修改同步服务器地址为阿里云
sed -i.bak '3,6d' /etc/chrony.conf && sed -i -e '3cserver ntp1.aliyun.com iburst' -i -e '/^#allow/callow 10.0.0.0/24' \
/etc/chrony.conf

# 启动chronyd及加入开机自启
systemctl start chronyd && systemctl enable chronyd

# 查看同步结果
$ chronyc sources
210 Number of sources = 1
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* 120.25.115.20                 2   6    37    13   +194us[+6131us] +/-   33ms

node节点操作

# 安装chrony
yum -y install chrony

# 修改同步服务器地址为k8s-master1
sed -i.bak '3,6d' /etc/chrony.conf && sed -i '3cserver k8s-master1 iburst' /etc/chrony.conf

# 启动chronyd及加入开机自启
systemctl start chronyd && systemctl enable chronyd

# 查看同步结果
$ chronyc sources
210 Number of sources = 1
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* k8s-master1                   3   6    17     5    +14us[  -17us] +/-   29ms

1.7 关闭swap分区

修改/etc/fstab文件,注释掉 SWAP 的自动挂载,使用free -m确认 swap 已经关闭

# 手动关闭swap
swapoff -a

# 修改fstab文件,注释swap自动挂载
sed -i '/^\/dev\/mapper\/centos-swap/c#/dev/mapper/centos-swap swap                    swap    defaults        0 0' /etc/fstab

# 查看swap是否关闭
$ free -m
total        used        free      shared  buff/cache   available
Mem:           1994         682         612           9         699        1086
Swap:             0           0           0

swappiness 参数调整,修改/etc/sysctl.d/k8s.conf添加下面一行

# 向文件中追加内容
cat >> /etc/sysctl.d/k8s.conf <<EOF
vm.swappiness=0
EOF

# 使配置生效
sysctl -p /etc/sysctl.d/k8s.conf

1.8 安装docker19.03.11

k8s-v1.19.3官方推荐安装的docker版本是19.03.11

1.卸载旧版本
yum remove -y docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest \
docker-latest-logrotate \
docker-logrotate \
docker-selinux \
docker-engine-selinux \
docker-engine

2.安装依赖包
yum install -y yum-utils device-mapper-persistent-data lvm2

3.添加阿里云yum源
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

4.查看可用版本
yum list docker-ce --showduplicates | sort -r

已加载插件:fastestmirror, langpacks
可安装的软件包
 * updates: mirrors.aliyun.com
Loading mirror speeds from cached hostfile
 * extras: mirrors.aliyun.com
docker-ce.x86_64            3:19.03.5-3.el7                     docker-ce-stable
docker-ce.x86_64            3:19.03.4-3.el7                     docker-ce-stable
。。。。。。
docker-ce.x86_64            3:18.09.9-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.8-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.7-3.el7                     docker-ce-stable
docker-ce.x86_64            3:18.09.6-3.el7                     docker-ce-stable
。。。。。。


5.安装docker19.03.11
yum install -y docker-ce-19.03.11 docker-ce-cli-19.03.11 containerd.io

6.启动docker并设置开机自启
systemctl enable docker && systemctl start docker

7.配置阿里云docker镜像加速
cat > /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://gqk8w9va.mirror.aliyuncs.com"]
}
EOF

8.配置完后重启docker
systemctl restart docker

9.查看加速
$ docker info
找到Registry Mirrors一行
Registry Mirrors:
 https://gqk8w9va.mirror.aliyuncs.com/

10.查看docker版本
$ docker version
Client: Docker Engine - Community
 Version:           19.03.4
 API version:       1.40
 Go version:        go1.12.10
 Git commit:        9013bf583a
 Built:             Fri Oct 18 15:52:22 2019
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.4
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.12.10
  Git commit:       9013bf583a
  Built:            Fri Oct 18 15:50:54 2019
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.2.13
  GitCommit:        7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

1.9 安装Kubeadm

需要科学上网

cat >/etc/yum.repos.d/kubernetes.repo<<EOF
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg
        https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
EOF

使用阿里云yum源

cat >/etc/yum.repos.d/kubernetes.repo <<EOF
[kubernetes]
name=Kubernetes
baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg
        http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

安装 kubeadm、kubelet、kubectl(阿里云yum源会随官方更新最新版,因此指定版本)

# 指定版本安装
yum -y install kubelet-1.19.3 kubeadm-1.19.3 kubectl-1.19.3

# 查看版本
$ kubeadm version
kubeadm version: &version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.4", GitCommit:"8d8aa39598534325ad77120c120a22b3a990b5ea", GitTreeState:"clean", BuildDate:"2020-03-12T21:01:11Z", GoVersion:"go1.13.8", Compiler:"gc", Platform:"linux/amd64"}

设置kubelet开机自启

⚠️此时kubelet是无法启动的,因为只有完成master的kubeadm init 的操作,kubelet才能正常启动

systemctl enable kubelet

设置k8s命令自动补全

yum -y install bash-completion
source /usr/share/bash-completion/bash_completion
source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> ~/.bashrc

1.10 修改docker Cgroup Driver为systemd

由于默认情况下 kubelet 使用的 cgroupdriver 是 systemd,所以需要保持 docker 和kubelet 的 cgroupdriver 一致,我们这里修改 docker 的 cgroupdriver=systemd。如果不修改 docker 则需要修改 kubelet 的启动配置,需要保证两者一致。

# 修改docker Cgroup Driver为systemd/usr/lib/systemd/system/docker.service文件中的这一行 ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

修改为 ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --exec-opt native.cgroupdriver=systemd

如果不修改,在添加 worker 节点时可能会碰到如下错误
[WARNING IsDockerSystemdCheck]: detected "cgroupfs" as the Docker cgroup driver. The recommended driver is "systemd". 
Please follow the guide at https://kubernetes.io/docs/setup/cri/


# 使用如下命令修改  
sed -i.bak "s#^ExecStart=/usr/bin/dockerd.*#ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --exec-opt native.cgroupdriver=systemd#g" /usr/lib/systemd/system/docker.service

# 重启docker
systemctl daemon-reload && systemctl restart docker

1.11 升级内核

centos7内核下载地址

可根据自己实际需求下载对应版本

iShot2020-10-20 14.25.34

现在升级到最新版,编辑安装最新内核脚本

cat > /opt/kernel_update.sh <<EOF
# 1.下载包
rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org && 
rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-3.el7.elrepo.noarch.rpm

# 2.默认安装为最新内核
yum -y install --enablerepo=elrepo-kernel kernel-ml

# 3.修改内核顺序
grub2-set-default 0 && grub2-mkconfig -o /etc/grub2.cfg

# 4.使用下面命令看看确认下是否启动默认内核指向上面安装的内核
grubby --default-kernel
export kernel_version=`grubby --default-kernel|awk -F'-' '{print $2}'`
echo -e "\e[42m安装的内核版本是 $kernel_version\e[0m"

# 5.重启机器生效
reboot
EOF


sh /opt/kernel_update.sh

到此,基本环境安装完成!!!

二、初始化集群

2.1 master节点操作,配置 kubeadm 初始化文件

可以通过如下命令导出默认的初始化配置

kubeadm config print init-defaults > kubeadm.yaml
  • 方法一
    • 命令初始化
kubeadm init --apiserver-advertise-address=10.0.0.130 --image-repository registry.aliyuncs.com/google_containers --kubernetes-version v1.19.3 --service-cidr=10.96.0.0/16 --pod-network-cidr=10.20.0.0/16

--apiserver-advertise-address=    #master节点IP
--image-repository registry.aliyuncs.com/google_containers #镜像仓库
--kubernetes-version v1.19.3    #k8s版本
--service-cidr=10.96.0.0/16        #service IP网段
--pod-network-cidr=10.20.0.0/16    #pod IP网段,后续网络插件会用到
  • 方法二
    • 文件初始化

官方清单说明文档

cat > kubeadm.yaml <<EOF
apiVersion: kubeadm.k8s.io/v1beta2
bootstrapTokens:
- groups:
  - system:bootstrappers:kubeadm:default-node-token
  token: abcdef.0123456789abcdef
  ttl: 24h0m0s
  usages:
  - signing
  - authentication
kind: InitConfiguration
localAPIEndpoint:
  advertiseAddress: 10.0.0.130  # apiserver 节点内网IP
  bindPort: 6443
nodeRegistration:
  criSocket: /var/run/dockershim.sock
  name: master1
  taints:
  - effect: NoSchedule
    key: node-role.kubernetes.io/master
---
apiServer:
  timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta2
certificatesDir: /etc/kubernetes/pki
clusterName: kubernetes
controllerManager: {}
dns:
  type: CoreDNS
etcd:
  local:
    dataDir: /var/lib/etcd
imageRepository: registry.aliyuncs.com/google_containers
# registry.aliyuncs.com/k8sxio   # 修改成阿里云镜像源
kind: ClusterConfiguration
kubernetesVersion: v1.19.3
networking:
  dnsDomain: cluster.local
  podSubnet: 10.244.0.0/16  # Pod 网段,flannel插件需要使用这个网段
  serviceSubnet: 10.96.0.0/12
scheduler: {}
---
apiVersion: kubeproxy.config.k8s.io/v1alpha1
kind: KubeProxyConfiguration
mode: ipvs  # kube-proxy 模式
EOF

2.2 初始化master

可以先将需要的镜像pull下来

kubeadm config images pull --config kubeadm.yaml

# 下载的镜像
[config/images] Pulled registry.aliyuncs.com/google_containers/kube-apiserver:v1.19.3
[config/images] Pulled registry.aliyuncs.com/google_containers/kube-controller-manager:v1.19.3
[config/images] Pulled registry.aliyuncs.com/google_containers/kube-scheduler:v1.19.3
[config/images] Pulled registry.aliyuncs.com/google_containers/kube-proxy:v1.19.3
[config/images] Pulled registry.aliyuncs.com/google_containers/pause:3.2
[config/images] Pulled registry.aliyuncs.com/google_containers/etcd:3.4.13-0
[config/images] Pulled registry.aliyuncs.com/google_containers/coredns:1.7.0

可以使用如下命令查看kubeadm需要的镜像列表

# 默认使用的是谷歌的镜像仓库
$ kubeadm config images list
W1020 15:34:00.813012    3391 configset.go:348] WARNING: kubeadm cannot validate component configs for API groups [kubelet.config.k8s.io kubeproxy.config.k8s.io]
k8s.gcr.io/kube-apiserver:v1.19.3
k8s.gcr.io/kube-controller-manager:v1.19.3
k8s.gcr.io/kube-scheduler:v1.19.3
k8s.gcr.io/kube-proxy:v1.19.3
k8s.gcr.io/pause:3.2
k8s.gcr.io/etcd:3.4.13-0
k8s.gcr.io/coredns:1.7.0

# 指定配置文件查看kubeadm需要下载的镜像
$ kubeadm config images list --config kubeadm.yaml
W1020 15:48:24.612354    3760 configset.go:348] WARNING: kubeadm cannot validate component configs for API groups [kubelet.config.k8s.io kubeproxy.config.k8s.io]
registry.aliyuncs.com/google_containers/kube-apiserver:v1.19.3
registry.aliyuncs.com/google_containers/kube-controller-manager:v1.19.3
registry.aliyuncs.com/google_containers/kube-scheduler:v1.19.3
registry.aliyuncs.com/google_containers/kube-proxy:v1.19.3
registry.aliyuncs.com/google_containers/pause:3.2
registry.aliyuncs.com/google_containers/etcd:3.4.13-0
registry.aliyuncs.com/google_containers/coredns:1.7.0

开始初始化集群

kubeadm init --config kubeadm.yaml
完整输出结果
W1020 15:53:56.503466    4046 configset.go:348] WARNING: kubeadm cannot validate component configs for API groups [kubelet.config.k8s.io kubeproxy.config.k8s.io]
[init] Using Kubernetes version: v1.19.3
[preflight] Running pre-flight checks
    [WARNING Hostname]: hostname "master1" could not be reached
    [WARNING Hostname]: hostname "master1": lookup master1 on 223.5.5.5:53: no such host
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "ca" certificate and key
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local master1] and IPs [10.96.0.1 10.0.0.130]
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "front-proxy-ca" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] Generating "etcd/ca" certificate and key
[certs] Generating "etcd/server" certificate and key
[certs] etcd/server serving cert is signed for DNS names [localhost master1] and IPs [10.0.0.130 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [localhost master1] and IPs [10.0.0.130 127.0.0.1 ::1]
[certs] Generating "etcd/healthcheck-client" certificate and key
[certs] Generating "apiserver-etcd-client" certificate and key
[certs] Generating "sa" key and public key
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[kubeconfig] Writing "admin.conf" kubeconfig file
[kubeconfig] Writing "kubelet.conf" kubeconfig file
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Starting the kubelet
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests"
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[apiclient] All control plane components are healthy after 13.002462 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.19" in namespace kube-system with the configuration for the kubelets in the cluster
[upload-certs] Skipping phase. Please see --upload-certs
[mark-control-plane] Marking the node master1 as control-plane by adding the label "node-role.kubernetes.io/master=''"
[mark-control-plane] Marking the node master1 as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: abcdef.0123456789abcdef
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to get nodes
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstrap-token] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstrap-token] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstrap-token] Creating the "cluster-info" ConfigMap in the "kube-public" namespace
[kubelet-finalize] Updating "/etc/kubernetes/kubelet.conf" to point to a rotatable kubelet client certificate and key
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your Kubernetes control-plane has initialized successfully!

To start using your cluster, you need to run the following as a regular user:

  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config

You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
  https://kubernetes.io/docs/concepts/cluster-administration/addons/

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

kubeadm join 10.0.0.130:6443 --token abcdef.0123456789abcdef \
    --discovery-token-ca-cert-hash sha256:9ef5d816512489579f88785e67a80fbd7cc73c65457dde935c69ff2bcaa6cd96

kubeadm init 命令执行流程如下图所示

iShot2020-10-20 16.02.59

# kubeadm config images pull --config kubeadm.yaml 下载的镜像
registry.aliyuncs.com/google_containers/kube-proxy                v1.19.3             cdef7632a242        5 days ago          118MB
registry.aliyuncs.com/google_containers/kube-controller-manager   v1.19.3             9b60aca1d818        5 days ago          111MB
registry.aliyuncs.com/google_containers/kube-scheduler            v1.19.3             aaefbfa906bd        5 days ago          45.7MB
registry.aliyuncs.com/google_containers/kube-apiserver            v1.19.3             a301be0cd44b        5 days ago          119MB
registry.aliyuncs.com/google_containers/etcd                      3.4.13-0            0369cf4303ff        7 weeks ago         253MB
registry.aliyuncs.com/google_containers/coredns                   1.7.0               bfe3a36ebd25        4 months ago        45.2MB
registry.aliyuncs.com/google_containers/pause                     3.2                 80d28bedfe5d        8 months ago        683kB


# kubeadm init --config kubeadm.yaml启动的容器
CONTAINER ID        IMAGE                                               COMMAND                  CREATED              STATUS              PORTS               NAMES
c79c4892da0b        cdef7632a242                                        "/usr/local/bin/kube…"   About a minute ago   Up About a minute                       k8s_kube-proxy_kube-proxy-tqtqg_kube-system_e9dcc574-d430-436c-9b30-04b72cd47b17_0
26a2ae82ef0e        registry.aliyuncs.com/google_containers/pause:3.2   "/pause"                 About a minute ago   Up About a minute                       k8s_POD_kube-proxy-tqtqg_kube-system_e9dcc574-d430-436c-9b30-04b72cd47b17_0
f77d83a7b547        aaefbfa906bd                                        "kube-scheduler --au…"   About a minute ago   Up About a minute                       k8s_kube-scheduler_kube-scheduler-master1_kube-system_285062c53852ebaf796eba8548d69e43_0
8c2c0fed9792        9b60aca1d818                                        "kube-controller-man…"   About a minute ago   Up About a minute                       k8s_kube-controller-manager_kube-controller-manager-master1_kube-system_8f99a56fb3eeae0c61283d6071bfb1f4_0
adab35c64481        a301be0cd44b                                        "kube-apiserver --ad…"   About a minute ago   Up About a minute                       k8s_kube-apiserver_kube-apiserver-master1_kube-system_20c1cf16863ba23269117625a41bbd61_0
107a0f8678b9        0369cf4303ff                                        "etcd --advertise-cl…"   About a minute ago   Up About a minute                       k8s_etcd_etcd-master1_kube-system_f98110a6164b8f0481572a8f9382951a_0
91c9349800c7        registry.aliyuncs.com/google_containers/pause:3.2   "/pause"                 About a minute ago   Up About a minute                       k8s_POD_kube-scheduler-master1_kube-system_285062c53852ebaf796eba8548d69e43_0
3585b984e1b9        registry.aliyuncs.com/google_containers/pause:3.2   "/pause"                 About a minute ago   Up About a minute                       k8s_POD_kube-controller-manager-master1_kube-system_8f99a56fb3eeae0c61283d6071bfb1f4_0
f23fe4ef6069        registry.aliyuncs.com/google_containers/pause:3.2   "/pause"                 About a minute ago   Up About a minute                       k8s_POD_kube-apiserver-master1_kube-system_20c1cf16863ba23269117625a41bbd61_0
09271e8da969        registry.aliyuncs.com/google_containers/pause:3.2   "/pause"                 About a minute ago   Up About a minute                       k8s_POD_etcd-master1_kube-system_f98110a6164b8f0481572a8f9382951a_0

拷贝 kubeconfig 文件

# 这里的路径为/root
mkdir -p $HOME/.kube
cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
chown $(id -u):$(id -g) $HOME/.kube/config

2.3 master添加节点

node1和node2相同操作

将master节点上的$HOME/.kube/config 文件拷贝到node节点对应的文件中

# 创建目录,这里的路径为/root
mkdir -p $HOME/.kube 

# 把master节点上的config文件拷贝到node1和node2的$HOME/.kube
scp k8s-master1:~/.kube/config $HOME/.kube

# 修改权限
chown $(id -u):$(id -g) $HOME/.kube/config

将node1和node2加入到集群中

这里需要用到2.2中初始化master最后生成的token和sha256值

kubeadm join 10.0.0.130:6443 --token abcdef.0123456789abcdef \
    --discovery-token-ca-cert-hash sha256:9ef5d816512489579f88785e67a80fbd7cc73c65457dde935c69ff2bcaa6cd96
输出结果  
[preflight] Running pre-flight checks
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Starting the kubelet
[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...

This node has joined the cluster:
* Certificate signing request was sent to apiserver and a response was received.
* The Kubelet was informed of the new secure connection details.

Run 'kubectl get nodes' on the control-plane to see this node join the cluster.

kubeadm join 命令执行流程如下所示

iShot2020-10-20 16.04.22

将node节点加入到k8s集群后,node节点会运行kube-proxy

# 下载的镜像
CONTAINER ID        IMAGE                                                COMMAND                  CREATED              STATUS              PORTS               NAMES
5d72febd6273        registry.aliyuncs.com/google_containers/kube-proxy   "/usr/local/bin/kube…"   About a minute ago   Up About a minute                       k8s_kube-proxy_kube-proxy-44bsb_kube-system_1501673e-9840-4f37-9ab3-690a2c673d0f_0
b94dc5408576        registry.aliyuncs.com/google_containers/pause:3.2    "/pause"                 2 minutes ago        Up


# 启动的容器
CONTAINER ID        IMAGE                                                COMMAND                  CREATED              STATUS              PORTS               NAMES
5d72febd6273        registry.aliyuncs.com/google_containers/kube-proxy   "/usr/local/bin/kube…"   About a minute ago   Up About a minute                       k8s_kube-proxy_kube-proxy-44bsb_kube-system_1501673e-9840-4f37-9ab3-690a2c673d0f_0
b94dc5408576        registry.aliyuncs.com/google_containers/pause:3.2    "/pause"                 2 minutes ago        Up 2 minutes                            k8s_POD_kube-proxy-44bsb_kube-system_1501673e-9840-4f37-9ab3-690a2c673d0f_0

如果忘记了token和sha256值,可以在master节点使用如下命令查看

# 查看token
$ kubeadm token list
TOKEN                     TTL         EXPIRES                     USAGES                   DESCRIPTION                                                EXTRA GROUPS
abcdef.0123456789abcdef   23h         2020-03-20T23:02:03+08:00   authentication,signing   <none>                                                     system:bootstrappers:kubeadm:default-node-token


# 查看sha256
$ openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //'
27b37276c4451b54c99106f73cb38c3b0bb6e2e178c142808e9ff00300ac7eaf


# 同时查看token和sha256
$ kubeadm token create --print-join-command
W1020 16:01:33.668459    7695 configset.go:348] WARNING: kubeadm cannot validate component configs for API groups [kubelet.config.k8s.io kubeproxy.config.k8s.io]
kubeadm join 10.0.0.130:6443 --token gmrizd.neccboizuq5ik6t4     --discovery-token-ca-cert-hash sha256:9ef5d816512489579f88785e67a80fbd7cc73c65457dde935c69ff2bcaa6cd96

master节点查看node,发现状态都是NotReady,因为还没有安装网络插件,这里我们安装

k8s网络插件官方文档

calio插件官方文档

$ kubectl get nodes
NAME         STATUS     ROLES    AGE     VERSION
k8s-master   NotReady   master   19m     v1.19.3
k8s-node1    NotReady   <none>   4m10s   v1.19.3
k8s-node2    NotReady   <none>   4m3s    v1.19.3

2.4 master节点安装网络插件calio

# 下载文件
wget https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

# 修改文件内容
搜索 kube-flannel-ds ,kube-flannel-ds 中 containers 下的 args 添加如下一行 - --iface=eth0
这么做是为了避免机器中是多网卡的情况,这里手动指定一下网卡名称

# 修改完成后安装flannel网络插件
kubectl apply -f kube-flannel.yml 

# 安装完成后稍等一会查看pods状态,全部为running即为正确
kubectl get pods -n kube-system

# 查看node状态
kubectl get nodes
NAME         STATUS   ROLES    AGE   VERSION
k8s-master   Ready    master   30m   v1.19.3
k8s-node1    Ready    <none>   25m   v1.19.3
k8s-node2    Ready    <none>   25m   v1.19.3

# kubectl apply -f kube-flannel.yml 安装网络插件flannel下载的镜像
REPOSITORY                                                        TAG                 IMAGE ID            CREATED             SIZE
quay.io/coreos/flannel                                            v0.13.0             e708f4bb69e3        5 days ago          57.2MB

# kubectl apply -f kube-flannel.yml 安装网络插件flannel启动的容器
CONTAINER ID        IMAGE                                               COMMAND                  CREATED             STATUS                     PORTS               NAMES
902867d66cdc        bfe3a36ebd25                                        "/coredns -conf /etc…"   2 minutes ago       Up 2 minutes                                   k8s_coredns_coredns-6d56c8448f-sm772_kube-system_12eb4ed7-e150-46bd-9269-44f67f757c10_0
b32d7e15eddc        bfe3a36ebd25                                        "/coredns -conf /etc…"   2 minutes ago       Up 2 minutes                                   k8s_coredns_coredns-6d56c8448f-pjdd7_kube-system_5ad83254-04b8-45b4-9c63-b811cccb1f60_0
5f2076eb19b0        registry.aliyuncs.com/google_containers/pause:3.2   "/pause"                 2 minutes ago       Up 2 minutes                                   k8s_POD_coredns-6d56c8448f-sm772_kube-system_12eb4ed7-e150-46bd-9269-44f67f757c10_0
e29468c30f1d        registry.aliyuncs.com/google_containers/pause:3.2   "/pause"                 2 minutes ago       Up 2 minutes                                   k8s_POD_coredns-6d56c8448f-pjdd7_kube-system_5ad83254-04b8-45b4-9c63-b811cccb1f60_0
48f9771ad558        e708f4bb69e3                                        "/opt/bin/flanneld -…"   2 minutes ago       Up 2 minutes                                   k8s_kube-flannel_kube-flannel-ds-njvkx_kube-system_9d9bbb3a-49bc-40cd-af35-8a1592534fb5_0
726ad34dd6ee        quay.io/coreos/flannel                              "cp -f /etc/kube-fla…"   2 minutes ago       Exited (0) 2 minutes ago                       k8s_install-cni_kube-flannel-ds-njvkx_kube-system_9d9bbb3a-49bc-40cd-af35-8a1592534fb5_0
4e5d65b8c80a        registry.aliyuncs.com/google_containers/pause:3.2   "/pause"                 2 minutes ago       Up 2 minutes                                   k8s_POD_kube-flannel-ds-njvkx_kube-system_9d9bbb3a-49bc-40cd-af35-8a1592534fb5_0

node节点

# 下载的镜像
REPOSITORY                                           TAG                 IMAGE ID            CREATED             SIZE
quay.io/coreos/flannel                               v0.13.0             e708f4bb69e3        5 days ago          57.2MB           

# 启动的容器
CONTAINER ID        IMAGE                                                COMMAND                  CREATED             STATUS                     PORTS               NAMES
6af151942c77        e708f4bb69e3                                         "/opt/bin/flanneld -…"   3 minutes ago       Up 3 minutes                                   k8s_kube-flannel_kube-flannel-ds-b5l9b_kube-system_d13d64c1-4564-4995-bbc1-aaabc34f76c0_0
9faa5e1b769f        quay.io/coreos/flannel                               "cp -f /etc/kube-fla…"   3 minutes ago       Exited (0) 3 minutes ago                       k8s_install-cni_kube-flannel-ds-b5l9b_kube-system_d13d64c1-4564-4995-bbc1-aaabc34f76c0_0
c16b48d309a2        registry.aliyuncs.com/google_containers/pause:3.2    "/pause"                 3 minutes ago       Up 3 minutes

2.5 安装Dashboard(可选)

下载文件及修改内容

这里查看dashboard对应的k8s版本

# 下载文件
wget https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.4/aio/deploy/recommended.yaml

# 修改Service为NodePort类型
42行下增加一行
nodePort: 30001

44行下增加一行
type: NodePort


//原先内容
spec:
  ports:
    - port: 443
      targetPort: 8443
  selector:
    k8s-app: kubernetes-dashboard


//修改后内容
spec:
  type: NodePort        #增加,修改类型为nodeport
  ports:
    - port: 443
      targetPort: 8443
      nodePort: 30001   #增加,指定nodeport端口
  selector:
    k8s-app: kubernetes-dashboard

部署dashboard

# 创建dashboard
kubectl apply -f recommended.yaml

# 下载的镜像
kubernetesui/dashboard                               v2.0.4              46d0a29c3f61        6 weeks ago         225MB

# 启动的容器
CONTAINER ID        IMAGE                    COMMAND                  CREATED             STATUS              PORTS               NAMES
f960c868c3e0        kubernetesui/dashboard   "/dashboard --insecu…"   41 seconds ago      Up 40 seconds                           k8s_kubernetes-dashboard_kubernetes-dashboard-665f4c5ff-8q4bt_kubernetes-dashboard_192980de-d658-4367-a720-fab16ebd62d0_0

查看dashboard的运行状态及外网访问端口

# 查看dashboard运行状态
$ kubectl get pods -n kubernetes-dashboard -l k8s-app=kubernetes-dashboard
NAME                                    READY   STATUS    RESTARTS   AGE
kubernetes-dashboard-7867cbccbb-z9vzj   1/1     Running   0          50s

# 查看dashboard外网访问端口
$ kubectl get svc -n kubernetes-dashboard -l k8s-app=kubernetes-dashboard
NAME                   TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)         AGE
kubernetes-dashboard   NodePort   10.102.116.245   <none>        443:30001/TCP   2m56s

通过上边的30001端口访问dashboard,注意是https

⚠️k8s1.19.3这个版本中,使用的dashboard版本是2.0.4,只有火狐浏览器可以访问,其余浏览器都不能访问,会报错如下

iShot2020-03-1722.09.59

只有火狐浏览器可以!

然后创建一个具有全局所有权限的用户来登录Dashboard

# 编辑admin.yaml文件
cat > admin.yaml <<EOF
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: admin
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
subjects:
- kind: ServiceAccount
  name: admin
  namespace: kubernetes-dashboard
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin
  namespace: kubernetes-dashboard
EOF

# 直接创建
kubectl apply -f admin.yaml

# 查看token
$ kubectl get secret -n kubernetes-dashboard|grep admin-token
admin-token-zcwfb                  kubernetes.io/service-account-token   3      52s

//获取base64解码后的字符串,注意需要用到上边命令查看到的token,会生成很长的一串字符串
kubectl get secret admin-token-zcwfb -o jsonpath={.data.token} -n kubernetes-dashboard |base64 -d

//直接用这条命令搞定
kubectl get secret `kubectl get secret -n kubernetes-dashboard | grep admin-token|awk '{print $1}'` -o jsonpath={.data.token} -n kubernetes-dashboard |base64 -d && echo

然后粘贴上述生成的base64字符串登陆dashboard,在登陆页面选择令牌一项

2

登陆后的首界面

1

2.6 安装kuboard(可选)

kuboard 是Kubernetes 的一款图形化管理界面

安装kuboard

kubectl apply -f https://kuboard.cn/install-script/kuboard.yaml
kubectl apply -f https://addons.kuboard.cn/metrics-server/0.3.7/metrics-server.yaml

查看运行状态

$ kubectl get pods -l k8s.kuboard.cn/name=kuboard -n kube-system
NAME                       READY   STATUS    RESTARTS   AGE
kuboard-756d46c4d4-tvhjq   1/1     Running   0          40s

获取token

# 获取管理员token
kubectl -n kube-system get secret $(kubectl -n kube-system get secret | grep kuboard-user | awk '{print $1}') -o go-template='{{.data.token}}' | base64 -d && echo


# 获取只读token
kubectl -n kube-system get secret $(kubectl -n kube-system get secret | grep kuboard-viewer | awk '{print $1}') -o go-template='{{.data.token}}' | base64 -d && echo

访问kuboard

Kuboard Service 使用了 NodePort 的方式暴露服务,NodePort 为 32567

k8s集群的任意一个节点都可以访问到

iShot2020-10-20 16.53.27

登陆后首界面

iShot2020-10-20 16.56.09

kuboard下载的镜像和启动的容器

# 启动的容器
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
6d765b5835b1        eipwork/kuboard     "/entrypoint.sh"    2 minutes ago       Up 2 minutes                            k8s_kuboard_kuboard-655785f55c-db5c4_kube-system_10f752b5-3434-468d-9e93-e8c76f81501a_0

# 下载的镜像,本文中为2.0.5版本
REPOSITORY                                           TAG                 IMAGE ID            CREATED             SIZE
eipwork/kuboard                                      latest              23b68e80aa82        12 days ago         182MB

到此,使用kubeadm安装k8s 1.19.3完成!!!

获取令牌命令

kubectl get secret `kubectl get secret -n kube-system|grep admin-token|awk '{print $1}'` -o jsonpath={.data.token} -n kube-system |base64 -d && echo

1.19.3master启动的容器及下载的镜像

下载的镜像

iShot2020-10-20 16.57.46

启动的容器

1.19.3node启动的容器和下载的镜像

node1下载的镜像

iShot2020-10-20 17.00.55

node1启动的容器

iShot2020-10-20 17.01.40

node2下载的镜像

iShot2020-10-20 17.01.40

node2启动的容器

iShot2020-10-20 17.05.27n

2.7 k8s切换命名空间工具(可选)

# 下载包
git clone https://github.com.cnpmjs.org/ahmetb/kubectx
cp kubectx/kubens /usr/local/bin

# 查看所有命名空间
$ kubens

# 切换到kube-system命名空间
$ kubens kube-system
Context "kubernetes-admin@kubernetes" modified.
Active namespace is "kube-system".
泡泡吐肥皂o © gitbook.pptfz.top 2021 all right reserved,powered by Gitbook文件修订时间: 秃笔南波湾!!!

results matching ""

    No results matching ""