使用Kubeadm安装Kubernetes 1.15

Hi, Everyone!Welcome to DQF's Blog,For technical exchange, Please add QQ: 905030209,Thanks!

kubeadm是Kubernetes官方提供的用于快速安装Kubernetes集群的工具,伴随Kubernetes每个版本的发布都会同步更新,kubeadm会对集群配置方面的一些实践做调整,通过实验kubeadm可以学习到Kubernetes官方在集群配置上一些新的最佳实践。

1. 准备

1.1 系统配置

在开始之前,部署Kubernetes集群机器需要满足以下几个条件:

  • 一台或多台机器,操作系统 CentOS7.x-86_x64
  • 硬件配置:2GB或更多RAM,2个CPU或更多CPU,单个CPU会有警告可以进行忽略,硬盘30GB或更多
  • 集群中所有机器之间网络互通
  • 可以访问外网,需要拉取镜像
  • 官方要求禁止swap分区,但可以进行忽略

本次实验中两台CentOS 7.6主机如下:

hostname ip role CPU MEM
test-1 10.0.0.11 master 1 2G
test-2 10.0.0.12 node01 1 2G

在hosts文件中添加主机解析

cat <<EOF >> /etc/hosts
10.0.0.11 test-1
10.0.0.12 test-2
EOF

如果各个主机启用了防火墙,需要开放Kubernetes各个组件所需要的端口,可以查看Installing kubeadm中的”Check required ports”一节。 这里简单起见在各节点禁用防火墙:

systemctl stop firewalld
systemctl disable firewalld

禁用SELINUX:

setenforce 0
vi /etc/selinux/config
SELINUX=disabled

创建/etc/sysctl.d/k8s.conf文件,目的为了k8s网络路由,添加如下内容:

cat <<EOF >> /etc/sysctl.d/k8s.conf
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

1.2 kube-proxy开启ipvs的前置条件

由于ipvs已经加入到了内核的主干,所以为kube-proxy开启ipvs的前提需要加载以下的内核模块:

ip_vs
ip_vs_rr
ip_vs_wrr
ip_vs_sh
nf_conntrack_ipv4

在所有的Kubernetes节点node1和node2上执行以下脚本:

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_ipv4
EOF
chmod 755 /etc/sysconfig/modules/ipvs.modules && bash /etc/sysconfig/modules/ipvs.modules && lsmod | grep -e ip_vs -e nf_conntrack_ipv4

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

接下来还需要确保各个节点上已经安装了ipset软件包yum install ipset。 为了便于查看ipvs的代理规则,最好安装一下管理工具ipvsadm yum install ipvsadm。

yum install -y ipset ipvsadm

如果以上前提条件如果不满足,则即使kube-proxy的配置开启了ipvs模式,也会退回到iptables模式。

1.3 安装Docker

Kubernetes从1.6开始使用CRI(Container Runtime Interface)容器运行时接口。默认的容器运行时仍然是Docker,使用的是kubelet中内置dockershim CRI实现。

安装docker的yum源:

wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo
yum install -y yum-utils device-mapper-persistent-data lvm2

查看最新的Docker版本:

yum list docker-ce.x86_64  --showduplicates |sort -r

Kubernetes 1.15当前支持的docker版本列表是1.13.1, 17.03, 17.06, 17.09, 18.06, 18.09。 这里在各节点安装docker的18.06.1版本。

yum -y install docker-ce-18.06.1.ce-3.el7
systemctl enable docker && systemctl start docker
docker --version
Docker version 18.06.1-ce, build e68fc7a

确认一下iptables filter表中FOWARD链的默认策略(pllicy)为ACCEPT:

iptables -nvL

iptables -P FORWARD ACCEPT 修改FORWARD策略为ACCEPT

1.4 修改docker cgroup driver为systemd

根据文档CRI installation中的内容,对于使用systemd作为init system的Linux的发行版,使用systemd作为docker的cgroup driver可以确保服务器节点在资源紧张的情况更加稳定,因此这里修改各个节点上docker的cgroup driver为systemd。

创建或修改/etc/docker/daemon.json:

cat <<EOF >>/etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"]
}
EOF

重启docker:

systemctl restart docker
docker info | grep Cgroup
Cgroup Driver: systemd # 结果展示

2. 使用kubeadm部署Kubernetes

2.1 安装kubeadm和kubelet

下面在各节点安装kubeadm和kubelet:

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

由于版本更新频繁,这里指定版本号部署:

yum install -y kubelet-1.15.0 kubeadm-1.15.0 kubectl-1.15.0
systemctl enable kubelet

从安装结果可以看出还安装了cri-tools, kubernetes-cni, socat三个依赖:

  • 官方从Kubernetes 1.14开始将cni依赖升级到了0.7.5版本
  • socat是kubelet的依赖
  • cri-tools是CRI(Container Runtime Interface)容器运行时接口的命令行工具
    运行kubelet –help可以看到原来kubelet的绝大多数命令行flag参数都被DEPRECATED了,如:
......
--address 0.0.0.0   The IP address for the Kubelet to serve on (set to 0.0.0.0 for all IPv4 interfaces and `::` for all IPv6 interfaces) (default 0.0.0.0) (DEPRECATED: This parameter should be set via the config file specified by the Kubelet's --config flag. See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-config-file/ for more information.)
......

而官方推荐我们使用–config指定配置文件,并在配置文件中指定原来这些flag所配置的内容。具体内容可以查看这里Set Kubelet parameters via a config file。这也是Kubernetes为了支持动态Kubelet配置(Dynamic Kubelet Configuration)才这么做的,参考Reconfigure a Node’s Kubelet in a Live Cluster

kubelet的配置文件必须是json或yaml格式,具体可查看这里

Kubernetes 1.8开始要求关闭系统的Swap,如果不关闭,默认配置下kubelet将无法启动。 关闭系统的Swap方法如下:

swapoff -a

修改 /etc/fstab 文件,注释掉 SWAP 的自动挂载,使用free -m确认swap已经关闭。 swappiness参数调整,修改/etc/sysctl.d/k8s.conf添加下面一行:

vm.swappiness=0

执行sysctl -p /etc/sysctl.d/k8s.conf使修改生效。

因为这里本次用于测试两台主机上还运行其他服务,关闭swap可能会对其他服务产生影响,所以这里修改kubelet的配置去掉这个限制。 使用kubelet的启动参数–fail-swap-on=false去掉必须关闭Swap的限制,修改/etc/sysconfig/kubelet,加入:

KUBELET_EXTRA_ARGS=--fail-swap-on=false

2.2 使用kubeadm init初始化集群

在各节点开机启动kubelet服务:

systemctl enable kubelet.service

使用kubeadm config print init-defaults可以打印集群初始化默认的使用的配置:

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: 1.2.3.4
  bindPort: 6443
nodeRegistration:
  criSocket: /var/run/dockershim.sock
  name: test-1
  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: k8s.gcr.io
kind: ClusterConfiguration
kubernetesVersion: v1.14.0
networking:
  dnsDomain: cluster.local
  serviceSubnet: 10.96.0.0/12
scheduler: {}

从默认的配置中可以看到,可以使用imageRepository定制在集群初始化时拉取k8s所需镜像的地址。基于默认配置定制出本次使用kubeadm初始化集群所需的配置文件kubeadm.yaml:

apiVersion: kubeadm.k8s.io/v1beta2
kind: InitConfiguration
localAPIEndpoint:
  advertiseAddress: 10.0.0.11
  bindPort: 6443
nodeRegistration:
  taints:
  - effect: PreferNoSchedule
    key: node-role.kubernetes.io/master
---
apiVersion: kubeadm.k8s.io/v1beta2
kind: ClusterConfiguration
kubernetesVersion: v1.15.0
networking:
  podSubnet: 10.244.0.0/16

使用kubeadm默认配置初始化的集群,会在master节点打上node-role.kubernetes.io/master:NoSchedule的污点,阻止master节点接受调度运行工作负载。这里测试环境只有两个节点,可以将这个taint修改为node-role.kubernetes.io/master:PreferNoSchedule。

在开始初始化集群之前可以使用kubeadm config images pull预先在各个节点上拉取所k8s需要的docker镜像。

接下来使用kubeadm初始化集群,此处我们用命令行初始化:

kubeadm init \
  --apiserver-advertise-address=10.0.0.11 \
  --image-repository registry.aliyuncs.com/google_containers \
  --kubernetes-version v1.15.0 \
  --pod-network-cidr=10.244.0.0/16 \
  --ignore-preflight-errors=NumCPU \
  --ignore-preflight-errors=Swap \
  --token-ttl 0 \ #设置token不过期
  --service-cidr=10.96.0.0/16  #可以自定义网络,此处选择默认

由于默认拉取镜像地址k8s.gcr.io国内无法访问,这里指定阿里云镜像仓库地址。
初始化结果如下:

[root@test-1 ~]# kubeadm init \
>   --apiserver-advertise-address=10.0.0.11 \
>   --image-repository registry.aliyuncs.com/google_containers \
>   --kubernetes-version v1.15.0 \
>   --pod-network-cidr=10.244.0.0/16 \
>   --ignore-preflight-errors=NumCPU \
>   --ignore-preflight-errors=Swap \
>   #  --service-cidr=10.1.0.0/16  #可以自定义网络,此处选择默认
[init] Using Kubernetes version: v1.15.0
[preflight] Running pre-flight checks
    [WARNING NumCPU]: the number of available CPUs 1 is less than the required 2
    [WARNING Swap]: running with swap on is not supported. Please disable swap
[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'
[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] Activating the kubelet service
[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 [test-1 kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 10.0.0.11]
[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 [test-1 localhost] and IPs [10.0.0.11 127.0.0.1 ::1]
[certs] Generating "etcd/healthcheck-client" certificate and key
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [test-1 localhost] and IPs [10.0.0.11 127.0.0.1 ::1]
[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
[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 24.505557 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.15" 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 test-1 as control-plane by adding the label "node-role.kubernetes.io/master=''"
[mark-control-plane] Marking the node test-1 as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: 1t22n5.3g5s44lxwqt2ce1q
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[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
[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.11:6443 --token 1t22n5.3g5s44lxwqt2ce1q \
    --discovery-token-ca-cert-hash sha256:438ad564086962a23b5869887e7ff28e162305cb8bf9a8708f329c2f07efb095 

上面记录了完成的初始化输出的内容,根据输出的内容基本上可以看出手动初始化安装一个Kubernetes集群所需要的关键步骤。 其中有以下关键内容:

  • [kubelet-start] 生成kubelet的配置文件”/var/lib/kubelet/config.yaml”
  • [certs]生成相关的各种证书
  • [kubeconfig]生成相关的kubeconfig文件
  • [control-plane]使用/etc/kubernetes/manifests目录中的yaml文件创建apiserver、controller-manager、scheduler的静态pod
  • [bootstraptoken]生成token记录下来,后边使用kubeadm join往集群中添加节点时会用到
  • 下面的命令是配置常规用户如何使用kubectl访问集群:
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
kubectl get nodes
  • 最后给出了将节点加入集群的命令kubeadm join 10.0.0.11:6443 –token 1t22n5.3g5s44lxwqt2ce1q \
    –discovery-token-ca-cert-hash sha256:438ad564086962a23b5869887e7ff28e162305cb8bf9a8708f329c2f07efb095

查看一下集群状态,确认个组件都处于healthy状态:

kubectl get cs
NAME                 STATUS    MESSAGE             ERROR
controller-manager   Healthy   ok                  
scheduler            Healthy   ok                  
etcd-0               Healthy   {"health":"true"}

集群初始化如果遇到问题,可以使用下面的命令进行清理:

kubeadm reset
ifconfig cni0 down
ip link delete cni0
ifconfig flannel.1 down
ip link delete flannel.1
rm -rf /var/lib/cni/

集群初始化忘记token后可以使用下面命令进行生成:

kubeadm token list
kubeadm token create

获取ca证书sha256编码hash值:

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

2.3 安装Pod Network

在安装网络之前,先查看node状态,此时状态应该为NotReady状态,安装完网络后为Ready状态

kubectl get nodes
NAME     STATUS     ROLES    AGE    VERSION
test-1   NotReady   master   103m   v1.15.0 

接下来安装flannel network add-on:

mkdir -p ~/k8s/
cd ~/k8s
curl -O https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
kubectl apply -f  kube-flannel.yml

clusterrole.rbac.authorization.k8s.io/flannel created
clusterrolebinding.rbac.authorization.k8s.io/flannel created
serviceaccount/flannel created
configmap/kube-flannel-cfg created
daemonset.extensions/kube-flannel-ds-amd64 created
daemonset.extensions/kube-flannel-ds-arm64 created
daemonset.extensions/kube-flannel-ds-arm created
daemonset.extensions/kube-flannel-ds-ppc64le created
daemonset.extensions/kube-flannel-ds-s390x created

这里注意kube-flannel.yml这个文件里的flannel的镜像是0.11.0,quay.io/coreos/flannel:v0.11.0-amd64
如果不能从quay下载,可以进行如下替换sed -i.bak 's#quay.io#quay-mirror.qiniu.com#g' kube-flannel.yml

如果Node有多个网卡的话,参考flannel issues 39701,目前需要在kube-flannel.yml中使用–iface参数指定集群主机内网网卡的名称,否则可能会出现dns无法解析。需要将kube-flannel.yml下载到本地,flanneld启动参数加上–iface=

containers:
      - name: kube-flannel
        image: quay.io/coreos/flannel:v0.11.0-amd64
        command:
        - /opt/bin/flanneld
        args:
        - --ip-masq
        - --kube-subnet-mgr
        - --iface=eth1
......

使用kubectl get pod --all-namespaces -o wide确保所有的Pod都处于Running状态。

kubectl get pod -n kube-system
NAME                             READY   STATUS    RESTARTS   AGE
coredns-bccdc95cf-lmzl5          1/1     Running   0          6h5m
coredns-bccdc95cf-p78f9          1/1     Running   0          6h5m
etcd-test-1                      1/1     Running   0          6h5m
kube-apiserver-test-1            1/1     Running   0          6h4m
kube-controller-manager-test-1   1/1     Running   0          6h4m
kube-flannel-ds-amd64-s779s      1/1     Running   0          16m
kube-proxy-m6lxs                 1/1     Running   0          6h5m
kube-scheduler-test-1            1/1     Running   0          6h4m

再次查看nodes状态,发现已完成Ready状态

kubectl get nodes
NAME     STATUS   ROLES    AGE    VERSION
test-1   Ready    master   6h4m   v1.15.0

2.4 向Kubernetes集群中添加Node节点

下面将test-2这个主机添加到Kubernetes集群中,在test-2上执行:

kubeadm join 10.0.0.11:6443 --token 1t22n5.3g5s44lxwqt2ce1q \
    --discovery-token-ca-cert-hash sha256:438ad564086962a23b5869887e7ff28e162305cb8bf9a8708f329c2f07efb095 \
    --ignore-preflight-errors=Swap --ignore-preflight-errors=NumCPU #添加-v=6查看详细init信息

主机test-2加入集群的日志如下:

kubeadm join

[root@test-2 ~]# kubeadm join 10.0.0.11:6443 --token zbdzqy.cjl80meb4ot9yku8  --discovery-token-ca-cert-hash sha256:438ad564086962a23b5869887e7ff28e162305cb8bf9a8708f329c2f07efb095     --ignore-preflight-errors=Swap --ignore-preflight-errors=NumCPU -v=6
I0826 14:24:49.755945    3061 join.go:364] [preflight] found NodeName empty; using OS hostname as NodeName
I0826 14:24:49.756015    3061 initconfiguration.go:105] detected and using CRI socket: /var/run/dockershim.sock
[preflight] Running pre-flight checks
I0826 14:24:49.756083    3061 preflight.go:91] [preflight] Running general checks
I0826 14:24:49.756119    3061 checks.go:254] validating the existence and emptiness of directory /etc/kubernetes/manifests
I0826 14:24:49.756144    3061 checks.go:292] validating the existence of file /etc/kubernetes/kubelet.conf
I0826 14:24:49.756149    3061 checks.go:292] validating the existence of file /etc/kubernetes/bootstrap-kubelet.conf
I0826 14:24:49.756155    3061 checks.go:105] validating the container runtime
I0826 14:24:49.847695    3061 checks.go:131] validating if the service is enabled and active
I0826 14:24:49.947301    3061 checks.go:341] validating the contents of file /proc/sys/net/bridge/bridge-nf-call-iptables
I0826 14:24:49.947343    3061 checks.go:341] validating the contents of file /proc/sys/net/ipv4/ip_forward
I0826 14:24:49.947363    3061 checks.go:653] validating whether swap is enabled or not
    [WARNING Swap]: running with swap on is not supported. Please disable swap
I0826 14:24:49.947425    3061 checks.go:382] validating the presence of executable ip
I0826 14:24:49.947448    3061 checks.go:382] validating the presence of executable iptables
I0826 14:24:49.947461    3061 checks.go:382] validating the presence of executable mount
I0826 14:24:49.947473    3061 checks.go:382] validating the presence of executable nsenter
I0826 14:24:49.947487    3061 checks.go:382] validating the presence of executable ebtables
I0826 14:24:49.947497    3061 checks.go:382] validating the presence of executable ethtool
I0826 14:24:49.947508    3061 checks.go:382] validating the presence of executable socat
I0826 14:24:49.947519    3061 checks.go:382] validating the presence of executable tc
I0826 14:24:49.947529    3061 checks.go:382] validating the presence of executable touch
I0826 14:24:49.947544    3061 checks.go:524] running all checks
I0826 14:24:49.970230    3061 checks.go:412] checking whether the given node name is reachable using net.LookupHost
I0826 14:24:49.970364    3061 checks.go:622] validating kubelet version
I0826 14:24:50.029484    3061 checks.go:131] validating if the service is enabled and active
I0826 14:24:50.038608    3061 checks.go:209] validating availability of port 10250
I0826 14:24:50.038802    3061 checks.go:292] validating the existence of file /etc/kubernetes/pki/ca.crt
I0826 14:24:50.038816    3061 checks.go:439] validating if the connectivity type is via proxy or direct
I0826 14:24:50.038849    3061 join.go:433] [preflight] Discovering cluster-info
I0826 14:24:50.038907    3061 token.go:199] [discovery] Trying to connect to API Server "10.0.0.11:6443"
I0826 14:24:50.039489    3061 token.go:74] [discovery] Created cluster-info discovery client, requesting info from "https://10.0.0.11:6443"
I0826 14:24:50.048659    3061 round_trippers.go:438] GET https://10.0.0.11:6443/api/v1/namespaces/kube-public/configmaps/cluster-info 200 OK in 9 milliseconds
I0826 14:24:50.051961    3061 token.go:140] [discovery] Requesting info from "https://10.0.0.11:6443" again to validate TLS against the pinned public key
I0826 14:24:50.061536    3061 round_trippers.go:438] GET https://10.0.0.11:6443/api/v1/namespaces/kube-public/configmaps/cluster-info 200 OK in 9 milliseconds
I0826 14:24:50.061878    3061 token.go:163] [discovery] Cluster info signature and contents are valid and TLS certificate validates against pinned roots, will use API Server "10.0.0.11:6443"
I0826 14:24:50.061891    3061 token.go:205] [discovery] Successfully established connection with API Server "10.0.0.11:6443"
I0826 14:24:50.061905    3061 join.go:447] [preflight] Fetching init configuration
I0826 14:24:50.061908    3061 join.go:480] [preflight] Retrieving KubeConfig objects
[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'
I0826 14:24:50.064879    3061 round_trippers.go:438] GET https://10.0.0.11:6443/api/v1/namespaces/kube-system/configmaps/kubeadm-config 200 OK in 2 milliseconds
I0826 14:24:50.067979    3061 round_trippers.go:438] GET https://10.0.0.11:6443/api/v1/namespaces/kube-system/configmaps/kube-proxy 200 OK in 1 milliseconds
I0826 14:24:50.078336    3061 round_trippers.go:438] GET https://10.0.0.11:6443/api/v1/namespaces/kube-system/configmaps/kubelet-config-1.15 200 OK in 8 milliseconds
I0826 14:24:50.080994    3061 interface.go:384] Looking for default routes with IPv4 addresses
I0826 14:24:50.081014    3061 interface.go:389] Default route transits interface "eth0"
I0826 14:24:50.081419    3061 interface.go:196] Interface eth0 is up
I0826 14:24:50.081534    3061 interface.go:244] Interface "eth0" has 3 addresses :[10.0.0.12/24 fe80::cfa4:bd51:f14a:14fc/64 fe80::23b0:1cd0:683f:1c23/64].
I0826 14:24:50.081563    3061 interface.go:211] Checking addr  10.0.0.12/24.
I0826 14:24:50.081572    3061 interface.go:218] IP found 10.0.0.12
I0826 14:24:50.081580    3061 interface.go:250] Found valid IPv4 address 10.0.0.12 for interface "eth0".
I0826 14:24:50.081587    3061 interface.go:395] Found active IP 10.0.0.12 
I0826 14:24:50.081700    3061 preflight.go:102] [preflight] Running configuration dependant checks
I0826 14:24:50.081714    3061 controlplaneprepare.go:214] [download-certs] Skipping certs download
I0826 14:24:50.081762    3061 kubelet.go:105] [kubelet-start] writing bootstrap kubelet config file at /etc/kubernetes/bootstrap-kubelet.conf
I0826 14:24:50.083679    3061 kubelet.go:113] [kubelet-start] writing CA certificate at /etc/kubernetes/pki/ca.crt
I0826 14:24:50.157044    3061 loader.go:359] Config loaded from file:  /etc/kubernetes/bootstrap-kubelet.conf
I0826 14:24:50.157563    3061 kubelet.go:131] [kubelet-start] Stopping the kubelet
[kubelet-start] Downloading configuration for the kubelet from the "kubelet-config-1.15" ConfigMap in the kube-system namespace
I0826 14:24:50.174362    3061 round_trippers.go:438] GET https://10.0.0.11:6443/api/v1/namespaces/kube-system/configmaps/kubelet-config-1.15 200 OK in 2 milliseconds
[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"
I0826 14:24:50.275494    3061 kubelet.go:148] [kubelet-start] Starting the kubelet
[kubelet-start] Activating the kubelet service
[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...
I0826 14:24:51.380069    3061 loader.go:359] Config loaded from file:  /etc/kubernetes/kubelet.conf
I0826 14:24:51.867488    3061 loader.go:359] Config loaded from file:  /etc/kubernetes/kubelet.conf
I0826 14:24:51.884185    3061 loader.go:359] Config loaded from file:  /etc/kubernetes/kubelet.conf
I0826 14:24:51.885054    3061 kubelet.go:166] [kubelet-start] preserving the crisocket information for the node
I0826 14:24:51.885070    3061 patchnode.go:30] [patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "test-2" as an annotation
I0826 14:24:52.397161    3061 round_trippers.go:438] GET https://10.0.0.11:6443/api/v1/nodes/test-2 404 Not Found in 10 milliseconds
I0826 14:24:52.888578    3061 round_trippers.go:438] GET https://10.0.0.11:6443/api/v1/nodes/test-2 200 OK in 2 milliseconds
I0826 14:24:52.899783    3061 round_trippers.go:438] PATCH https://10.0.0.11:6443/api/v1/nodes/test-2 200 OK in 8 milliseconds

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.

在管理节点查看nodes状态如下即加入成功:

[root@test-1 ~]# kubectl get nodes
NAME     STATUS   ROLES    AGE   VERSION
test-1   Ready    master   14d   v1.15.0
test-2   Ready    <none>   96s   v1.15.0

2.5 测试集群DNS可用性

用kubectl创建一个pod进行测试:

kubectl run curl --image=radial/busyboxplus:curl -it
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
If you don't see a command prompt, try pressing enter.
[ root@curl-5cc7b478b6-r997p:/ ]$

进入后执行nslookup kubernetes.default确认解析正常:

nslookup kubernetes.default
Server:    10.96.0.10
Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local

Name:      kubernetes.default
Address 1: 10.96.0.1 kubernetes.default.svc.cluster.local

2.6 从集群中移除Node

如果需要从集群中移除node2这个Node执行下面的命令:

在master节点上执行:

kubectl drain test-2 --delete-local-data --force --ignore-daemonsets
kubectl delete node test-2

移除节点信息如下:

kubectl drain test-2

[root@test-1 ~]# kubectl drain test-2 --delete-local-data --force --ignore-daemonsets
node/test-2 cordoned
WARNING: ignoring DaemonSet-managed Pods: kube-system/kube-flannel-ds-amd64-xfcvl, kube-system/kube-proxy-cx52m
evicting pod "curl-6bf6db5c4f-6lklr"
pod/curl-6bf6db5c4f-6lklr evicted
node/test-2 evicted
[root@test-1 ~]# kubectl get nodes
NAME     STATUS                        ROLES    AGE     VERSION
test-1   Ready                         master   18d     v1.15.0
test-2   NotReady,SchedulingDisabled      3d19h   v1.15.0
[root@test-1 ~]# kubectl delete node test-2
node "test-2" deleted

在node2上执行:

kubeadm reset
ifconfig cni0 down
ip link delete cni0
ifconfig flannel.1 down
ip link delete flannel.1
rm -rf /var/lib/cni/

移除节点信息如下:

test-2 kubeadm reset

[root@test-2 ~]# kubeadm reset
[reset] WARNING: Changes made to this host by 'kubeadm init' or 'kubeadm join' will be reverted.
[reset] Are you sure you want to proceed? [y/N]: y
[preflight] Running pre-flight checks
[reset] WARNING: Changes made to this host by 'kubeadm init' or 'kubeadm join' will be reverted.
[reset] Are you sure you want to proceed? [y/N]: y
[preflight] Running pre-flight checks
[reset] Stopping the kubelet service
[reset] Unmounting mounted directories in "/var/lib/kubelet"
[reset] Deleting contents of config directories: [/etc/kubernetes/manifests /etc/kubernetes/pki]
[reset] Deleting files: [/etc/kubernetes/admin.conf /etc/kubernetes/kubelet.conf /etc/kubernetes/bootstrap-kubelet.conf /etc/kubernetes/controller-manager.conf /etc/kubernetes/scheduler.conf]
[reset] Deleting contents of stateful directories: [/var/lib/kubelet /etc/cni/net.d /var/lib/dockershim /var/run/kubernetes]

The reset process does not reset or clean up iptables rules or IPVS tables.
If you wish to reset iptables, you must do so manually.
For example:
iptables -F && iptables -t nat -F && iptables -t mangle -F && iptables -X  

If your cluster was setup to utilize IPVS, run ipvsadm --clear (or similar)
to reset your system's IPVS tables.  

The reset process does not clean your kubeconfig files and you must remove them manually.
Please, check the contents of the $HOME/.kube/config file.

在node1上执行:

kubectl delete node test-2

2.7 kube-proxy开启ipvs

修改ConfigMap的kube-system/kube-proxy中的config.conf,mode: “ipvs”

kubectl edit cm kube-proxy -n kube-system


之后重启各个节点上的kube-proxy pod:

kubectl get pod -n kube-system | grep kube-proxy | awk '{system("kubectl delete pod "$1" -n kube-system")}'

awk '{system("kubectl delete pod "$1" -n kube-system")}' system表示执行括号里面的命令

再次查看各节点上的kube-proxy pod网络状态:

kubectl get pod -n kube-system | grep kube-proxy
[root@test-1 ~]# kubectl get pod -n kube-system | grep kube-proxy
kube-proxy-l47kb                 1/1     Running   0          3m3s
kube-proxy-mgc6l                 1/1     Running   0          3m

[root@test-1 ~]# kubectl logs kube-proxy-l47kb -n kube-system
I0830 02:34:32.761880       1 server_others.go:170] Using ipvs Proxier.
W0830 02:34:32.762129       1 proxier.go:401] IPVS scheduler not specified, use rr by default
I0830 02:34:32.762288       1 server.go:534] Version: v1.15.0
I0830 02:34:32.771588       1 conntrack.go:52] Setting nf_conntrack_max to 131072
I0830 02:34:32.775305       1 config.go:187] Starting service config controller
I0830 02:34:32.775334       1 controller_utils.go:1029] Waiting for caches to sync for service config controller
I0830 02:34:32.775368       1 config.go:96] Starting endpoints config controller
I0830 02:34:32.775379       1 controller_utils.go:1029] Waiting for caches to sync for endpoints config controller
I0830 02:34:32.875796       1 controller_utils.go:1036] Caches are synced for endpoints config controller
I0830 02:34:32.875847       1 controller_utils.go:1036] Caches are synced for service config controller

日志中打印出了Using ipvs Proxier,说明ipvs模式已经开启。

3. Kubernetes常用组件部署

越来越多的公司和团队开始使用Helm这个Kubernetes的包管理器,这里也将使用Helm安装Kubernetes的常用组件。

3.1 Helm的安装

Helm由客户端命helm令行工具和服务端tiller组成,Helm的安装十分简单。 下载helm命令行工具到master节点test-1的/usr/local/bin下,这里下载的2.14.1版本:

curl -O https://get.helm.sh/helm-v2.14.1-linux-amd64.tar.gz
tar -zxvf helm-v2.14.1-linux-amd64.tar.gz
cd linux-amd64/
cp helm /usr/local/bin/

为了安装服务端tiller,还需要在这台机器上配置好kubectl工具和kubeconfig文件,确保kubectl工具可以在这台机器上访问apiserver且正常使用。 这里的node1节点已经配置好了kubectl。

因为Kubernetes APIServer开启了RBAC访问控制,所以需要创建tiller使用的service account: tiller并分配合适的角色给它。 详细内容可以查看helm文档中的Role-based Access Control。 这里简单起见直接分配cluster-admin这个集群内置的ClusterRole给它。创建helm-rbac.yaml文件:

cat <<EOF >>helm-rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: tiller
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: tiller
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
  - kind: ServiceAccount
    name: tiller
    namespace: kube-system
EOF

执行create helm-rbac.yaml结果如下:

[root@test-1 k8s]# kubectl create -f helm-rbac.yaml 
serviceaccount/tiller created
clusterrolebinding.rbac.authorization.k8s.io/tiller created

接下来使用helm部署tiller:

helm init --service-account tiller --skip-refresh

输出信息如下:

helm init

[root@test-1 k8s]# helm init --service-account tiller --skip-refresh
Creating /root/.helm 
Creating /root/.helm/repository 
Creating /root/.helm/repository/cache 
Creating /root/.helm/repository/local 
Creating /root/.helm/plugins 
Creating /root/.helm/starters 
Creating /root/.helm/cache/archive 
Creating /root/.helm/repository/repositories.yaml 
Adding stable repo with URL: https://kubernetes-charts.storage.googleapis.com 
Adding local repo with URL: http://127.0.0.1:8879/charts 
$HELM_HOME has been configured at /root/.helm.

Tiller (the Helm server-side component) has been installed into your Kubernetes Cluster.

Please note: by default, Tiller is deployed with an insecure 'allow unauthenticated users' policy.
To prevent this, run `helm init` with the --tiller-tls-verify flag.
For more information on securing your installation see: https://docs.helm.sh/using_helm/#securing-your-helm-installation


tiller默认被部署在k8s集群中的kube-system这个namespace下:

[root@test-1 k8s]# kubectl get pod -n kube-system -l app=helm
NAME                             READY   STATUS             RESTARTS   AGE
tiller-deploy-7bf78cdbf7-rdm9q   0/1     ImagePullBackOff   0          4m51s

发现该状态为镜像拉取失败,通过kubectl describe命令查看详细信息:

Events:
  Type     Reason                  Age                            From             Message
  ----     ------                  ----                           ----             -------
  Warning  Failed                  3h12m (x496 over 5h12m)        kubelet, test-2  Error: ImagePullBackOff
  Warning  Failed                  57m (x3 over <invalid>)        kubelet, test-2  Error: ErrImagePull
  Warning  Failed                  57m (x3 over <invalid>)        kubelet, test-2  Failed to pull image "gcr.io/kubernetes-helm/tiller:v2.14.1": rpc error: code = Unknown desc = Error response from daemon: Get https://gcr.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)

需要成功拉取到镜像才能完成,大家可以通过这个地址进行拉取:docker pull smiledou123/tiller:v2.14.1,然后更改tag即可使用docker tag smiledou123/tiller:v2.14.1 gcr.io/kubernetes-helm/tiller:v2.14.1,再次查看状态如下:

[root@test-1 ~]# kubectl get pod -n kube-system -l app=helm
NAME                             READY   STATUS    RESTARTS   AGE
tiller-deploy-7bf78cdbf7-rdm9q   1/1     Running   0          5h15m

查看helm version状态:

[root@test-1 ~]# helm version
Client: &version.Version{SemVer:"v2.14.1", GitCommit:"5270352a09c7e8b6e8c9593002a73535276507c0", GitTreeState:"clean"}
Server: &version.Version{SemVer:"v2.14.1", GitCommit:"5270352a09c7e8b6e8c9593002a73535276507c0", GitTreeState:"clean"}

注意由于某些原因需要网络可以访问 gcr.io和 kubernetes-charts.storage.googleapis.com, 如果无法访问可以通过helm init –service-account tiller –tiller-image /tiller:v2.13.1 –skip-refresh使用私有镜像仓库中的tiller镜像,替换tiller镜像方法

查询helm chart仓库的地址:

helm repo list

测试是否与仓库地址通信:

[root@test-1 ~]# helm repo list
NAME    URL                                             
stable  https://kubernetes-charts.storage.googleapis.com
local   http://127.0.0.1:8879/charts                    
[root@test-1 ~]# ping kubernetes-charts.storage.googleapis.com
PING storage.l.googleusercontent.com (172.217.160.112) 56(84) bytes of data.
64 bytes from tsa03s06-in-f16.1e100.net (172.217.160.112): icmp_seq=1 ttl=128 time=61.0 ms
64 bytes from tsa03s06-in-f16.1e100.net (172.217.160.112): icmp_seq=2 ttl=128 time=59.3 ms
64 bytes from tsa03s06-in-f16.1e100.net (172.217.160.112): icmp_seq=3 ttl=128 time=60.1 ms

如果发现不能与helm 仓库通信可以进行如下命令修改仓库地址:

helm repo add stable http://mirror.azure.cn/kubernetes/charts

3.2 使用Helm部署Nginx Ingress

为了便于将集群中的服务暴露到集群外部,需要使用Ingress。接下来使用Helm将Nginx Ingress部署到Kubernetes上。 Nginx Ingress Controller被部署在Kubernetes的边缘节点上,关于Kubernetes边缘节点的高可用相关的内容可以查看之前整理的Bare metal环境下Kubernetes Ingress边缘节点的高可用,Ingress Controller使用hostNetwork

我们将node1(10.0.0.11)做为边缘节点,打上Label后查看node信息:

kubectl label node test-1 node-role.kubernetes.io/edge=
kubectl get nodes

设置边缘节点输出信息如下:

[root@test-1 ~]# kubectl label node test-1 node-role.kubernetes.io/edge=
node/test-1 labeled
[root@test-1 ~]# kubectl get nodes
NAME     STATUS   ROLES         AGE   VERSION
test-1   Ready    edge,master   18d   v1.15.0
test-2   Ready    <none>        9h    v1.15.0

编辑nginx-ingress.yaml文件:

cat nginx-ingress.yaml

controller:
  replicaCount: 1
  hostNetwork: true
  nodeSelector:
    node-role.kubernetes.io/edge: ''
  affinity:
    podAntiAffinity:
        requiredDuringSchedulingIgnoredDuringExecution:
        - labelSelector:
            matchExpressions:
            - key: app
              operator: In
              values:
              - nginx-ingress
            - key: component
              operator: In
              values:
              - controller
          topologyKey: kubernetes.io/hostname
  tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: PreferNoSchedule
defaultBackend:
  nodeSelector:
    node-role.kubernetes.io/edge: ''
  tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: PreferNoSchedule

nginx ingress controller的副本数replicaCount为1,将被调度到test-1这个边缘节点上。这里并没有指定nginx ingress controller service的externalIPs,而是通过hostNetwork: true设置nginx ingress controller使用宿主机网络。

使用helm安装nginx-ingress:

helm repo update

helm install stable/nginx-ingress \
-n nginx-ingress \
--namespace ingress-nginx  \
-f ingress-nginx.yaml

输出日志如下:

helm install nginx-ingress

[root@test-1 k8s]# helm install stable/nginx-ingress -n nginx-ingress --namespace ingress-nginx  -f ingress-nginx.yaml
NAME:   nginx-ingress
LAST DEPLOYED: Fri Aug 30 19:33:09 2019
NAMESPACE: ingress-nginx
STATUS: DEPLOYED

RESOURCES:
==> v1/Pod(related)
NAME                                            READY  STATUS             RESTARTS  AGE
nginx-ingress-controller-598c7fd878-xwxhh       0/1    ContainerCreating  0         0s
nginx-ingress-default-backend-7b8b45bd49-4m4jp  0/1    ContainerCreating  0         0s

==> v1/Service
NAME                           TYPE          CLUSTER-IP    EXTERNAL-IP  PORT(S)                     AGE
nginx-ingress-controller       LoadBalancer  10.105.68.87      80:30672/TCP,443:30123/TCP  0s
nginx-ingress-default-backend  ClusterIP     10.96.106.96         80/TCP                      0s

==> v1/ServiceAccount
NAME           SECRETS  AGE
nginx-ingress  1        0s

==> v1beta1/ClusterRole
NAME           AGE
nginx-ingress  0s

==> v1beta1/ClusterRoleBinding
NAME           AGE
nginx-ingress  0s

==> v1beta1/Deployment
NAME                           READY  UP-TO-DATE  AVAILABLE  AGE
nginx-ingress-controller       0/1    1           0          0s
nginx-ingress-default-backend  0/1    1           0          0s

==> v1beta1/Role
NAME           AGE
nginx-ingress  0s

==> v1beta1/RoleBinding
NAME           AGE
nginx-ingress  0s


NOTES:
The nginx-ingress controller has been installed.
It may take a few minutes for the LoadBalancer IP to be available.
You can watch the status by running 'kubectl --namespace ingress-nginx get services -o wide -w nginx-ingress-controller'

An example Ingress that makes use of the controller:

  apiVersion: extensions/v1beta1
  kind: Ingress
  metadata:
    annotations:
      kubernetes.io/ingress.class: nginx
    name: example
    namespace: foo
  spec:
    rules:
      - host: www.example.com
        http:
          paths:
            - backend:
                serviceName: exampleService
                servicePort: 80
              path: /
    # This section is only required if TLS is to be enabled for the Ingress
    tls:
        - hosts:
            - www.example.com
          secretName: example-tls

If TLS is enabled for the Ingress, a Secret containing the certificate and key must also be provided:

  apiVersion: v1
  kind: Secret
  metadata:
    name: example-tls
    namespace: foo
  data:
    tls.crt: 
    tls.key: 
  type: kubernetes.io/tls

查看ingress-nginx状态:

[root@test-1 k8s]# kubectl get pod -n ingress-nginx -o wide
NAME                                             READY   STATUS              RESTARTS   AGE     IP          NODE     NOMINATED NODE   READINESS GATES
nginx-ingress-controller-598c7fd878-xwxhh        0/1     ContainerCreating   0          9m23s   10.0.0.11   test-1   <none>           <none>
nginx-ingress-default-backend-7b8b45bd49-4m4jp   0/1     ContainerCreating   0          9m23s   <none>      test-1   <none>           <none>

根据状态查看日志信息:

[root@test-1 k8s]# kubectl  describe pod nginx-ingress-controller-598c7fd878-xwxhh -n ingress-nginx
Name:           nginx-ingress-controller-598c7fd878-xwxhh
Namespace:      ingress-nginx
Priority:       0
Node:           test-1/10.0.0.11
Start Time:     Fri, 30 Aug 2019 19:33:10 +0800
Labels:         app=nginx-ingress
                component=controller
                pod-template-hash=598c7fd878
                release=nginx-ingress
......
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  10m   default-scheduler  Successfully assigned ingress-nginx/nginx-ingress-controller-598c7fd878-xwxhh to test-1
  Normal  Pulling    10m   kubelet, test-1    Pulling image "quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.25.1"

根据事件描述信息,推断可能是镜像无法下载,需要进行下载,为了下载方便,可以按照如下命令即可:

docker pull smiledou123/defaultbackend-amd64:1.5
docker tag smiledou123/defaultbackend-amd64:1.5 k8s.gcr.io/defaultbackend-amd64:1.5
docker pull smiledou123/nginx-ingress-controller:0.25.1
docker tag smiledou123/nginx-ingress-controller:0.25.1 quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.25.1

再次查看即可发现状态正常:

[root@test-1 k8s]# kubectl get pod -n ingress-nginx -o wide
NAME                                             READY   STATUS    RESTARTS   AGE   IP            NODE     NOMINATED NODE   READINESS GATES
nginx-ingress-controller-598c7fd878-xwxhh        1/1     Running   0          43m   10.0.0.11     test-1   <none>           <none>
nginx-ingress-default-backend-7b8b45bd49-4m4jp   1/1     Running   0          43m   10.244.0.16   test-1   <none>           <none>

如果访问http://10.0.0.11返回default backend,则部署完成。

3.3 使用Helm部署dashboard

编辑kubernetes-dashboard.yaml:

cat <<EOF >>/root/k8s/kubernetes-dashboard.yaml
image:
  repository: k8s.gcr.io/kubernetes-dashboard-amd64
  tag: v1.10.1
ingress:
  enabled: true
  hosts: 
    - k8s.frognew.com
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
  tls:
    - secretName: frognew-com-tls-secret
      hosts:
      - k8s.frognew.com
nodeSelector:
    node-role.kubernetes.io/edge: ''
tolerations:
    - key: node-role.kubernetes.io/master
      operator: Exists
      effect: NoSchedule
    - key: node-role.kubernetes.io/master
      operator: Exists
      effect: PreferNoSchedule
rbac:
  clusterAdminRole: true
EOF
helm install stable/kubernetes-dashboard \
-n kubernetes-dashboard \
--namespace kube-system  \
-f kubernetes-dashboard.yaml
helm install stable/kubernetes-dashboard

NAME:   kubernetes-dashboard
LAST DEPLOYED: Fri Aug 30 20:23:27 2019
NAMESPACE: kube-system
STATUS: DEPLOYED

RESOURCES:
==> v1/Deployment
NAME                  READY  UP-TO-DATE  AVAILABLE  AGE
kubernetes-dashboard  0/1    1           0          1s

==> v1/Pod(related)
NAME                                   READY  STATUS   RESTARTS  AGE
kubernetes-dashboard-848b8dd798-gptsk  0/1    Pending  0         0s

==> v1/Secret
NAME                  TYPE    DATA  AGE
kubernetes-dashboard  Opaque  0     1s

==> v1/Service
NAME                  TYPE       CLUSTER-IP      EXTERNAL-IP  PORT(S)  AGE
kubernetes-dashboard  ClusterIP  10.104.174.207         443/TCP  1s

==> v1/ServiceAccount
NAME                  SECRETS  AGE
kubernetes-dashboard  1        1s

==> v1beta1/ClusterRoleBinding
NAME                  AGE
kubernetes-dashboard  1s

==> v1beta1/Ingress
NAME                  HOSTS            ADDRESS  PORTS  AGE
kubernetes-dashboard  k8s.frognew.com  80, 443  1s


NOTES:
*********************************************************************************
*** PLEASE BE PATIENT: kubernetes-dashboard may take a few minutes to install ***
*********************************************************************************
From outside the cluster, the server URL(s) are:
     https://k8s.frognew.com

查看状态:

kubectl -n kube-system get secret | grep kubernetes-dashboard-token
[root@test-1 k8s]# kubectl describe -n kube-system secret/kubernetes-dashboard-token-qkxl4
Name:         kubernetes-dashboard-token-qkxl4
Namespace:    kube-system
Labels:       <none>
Annotations:  kubernetes.io/service-account.name: kubernetes-dashboard
              kubernetes.io/service-account.uid: 1b8f4e0f-afaf-4b5b-ada5-f7bb0f3e23bf

Type:  kubernetes.io/service-account-token

Data
====
ca.crt:     1025 bytes
namespace:  11 bytes
token:      eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJrdWJlcm5ldGVzLWRhc2hib2FyZC10b2tlbi1xa3hsNCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJrdWJlcm5ldGVzLWRhc2hib2FyZCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjFiOGY0ZTBmLWFmYWYtNGI1Yi1hZGE1LWY3YmIwZjNlMjNiZiIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDprdWJlLXN5c3RlbTprdWJlcm5ldGVzLWRhc2hib2FyZCJ9.QD2LDgZverXB7Zno9w-LDUpgpoNvQRVUCL5ZfsVO8ZyygujTwDRCKyxy_SUHDrFC5aewitPW_kJ0bencZ_WL5igU6ExkVLmtQQ8wZ_SGIRQBDxXmZbHGyG_8Swkzb8k5mILMrYzfve_XqmqVDrjhr_87boz8AYAMqcM6w5nJa4hwYzaVdJHjs0Xj4jo7ayo25dIT8nR8Z6IP78fzFaCr3L4i1lcc0OcsGlOGNHNqHOQU8-j55UlMgyhU28lnP7yO05tP5G8kdNDmy6IvgUJLGev6qUa1aovfM_PcWUzAKnvLnevMTZOLwPAV2ICms9BElcV5kFxQWLpZ6hrzcxYiig

查看token:

kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep kubernetes-dashboard-token|awk '{print $1}')|grep token:|awk '{print $2}'

通过浏览器访问k8s.frognew.com,选择令牌方式输入后进行访问:

在dashboard的登录窗口使用上面的token登录后如下界面:

3.4 使用Helm部署metrics-server

从Heapster的github https://github.com/kubernetes/heapster中可以看到已经,heapster已经DEPRECATED。 这里是heapster的deprecation timeline。 可以看出heapster从Kubernetes 1.12开始从Kubernetes各种安装脚本中移除。

Kubernetes推荐使用metrics-server。我们这里也使用helm来部署metrics-server。

编辑metrics-server.yaml文件:

cat <<EOF >>/root/k8s/metrics-server.yaml
args:
- --logtostderr
- --kubelet-insecure-tls
- --kubelet-preferred-address-types=InternalIP
nodeSelector:
    node-role.kubernetes.io/edge: ''
tolerations:
    - key: node-role.kubernetes.io/master
      operator: Exists
      effect: NoSchedule
    - key: node-role.kubernetes.io/master
      operator: Exists
      effect: PreferNoSchedule
EOF

helm install stable/metrics-server:

helm install stable/metrics-server \
-n metrics-server \
--namespace kube-system \
-f /root/k8s/metrics-server.yaml
helm install metrics-server

[root@test-1 k8s]# helm install stable/metrics-server \
> -n metrics-server \
> --namespace kube-system \
> -f /root/k8s/metrics-server.yaml
NAME:   metrics-server
LAST DEPLOYED: Fri Aug 30 21:05:36 2019
NAMESPACE: kube-system
STATUS: DEPLOYED

RESOURCES:
==> v1/ClusterRole
NAME                                     AGE
system:metrics-server                    2s
system:metrics-server-aggregated-reader  2s

==> v1/ClusterRoleBinding
NAME                                  AGE
metrics-server:system:auth-delegator  2s
system:metrics-server                 2s

==> v1/Deployment
NAME            READY  UP-TO-DATE  AVAILABLE  AGE
metrics-server  0/1    1           0          2s

==> v1/Pod(related)
NAME                             READY  STATUS             RESTARTS  AGE
metrics-server-8456fb6676-nnzcj  0/1    ContainerCreating  0         1s

==> v1/Service
NAME            TYPE       CLUSTER-IP    EXTERNAL-IP  PORT(S)  AGE
metrics-server  ClusterIP  10.98.211.25         443/TCP  2s

==> v1/ServiceAccount
NAME            SECRETS  AGE
metrics-server  1        2s

==> v1beta1/APIService
NAME                    AGE
v1beta1.metrics.k8s.io  2s

==> v1beta1/RoleBinding
NAME                        AGE
metrics-server-auth-reader  2s


NOTES:
The metric server has been deployed. 

In a few minutes you should be able to list metrics using the following
command:

  kubectl get --raw "/apis/metrics.k8s.io/v1beta1/nodes"

使用下面的命令可以获取到关于集群节点基本的指标信息:

kubectl get pods -n kube-system -o wide
kubectl top node
kubectl top pod -n kube-system

相关信息如下:

[root@test-1 ~]# kubectl top node
NAME     CPU(cores)   CPU%   MEMORY(bytes)   MEMORY%   
test-1   115m         11%    1231Mi          65%       
test-2   24m          2%     291Mi           15%       
[root@test-1 ~]# kubectl top pod -n kube-system
NAME                                    CPU(cores)   MEMORY(bytes)   
coredns-bccdc95cf-lmzl5                 2m           15Mi            
coredns-bccdc95cf-p78f9                 2m           13Mi            
etcd-test-1                             8m           61Mi            
kube-apiserver-test-1                   19m          323Mi           
kube-controller-manager-test-1          8m           71Mi            
kube-flannel-ds-amd64-2pdp5             2m           9Mi             
kube-flannel-ds-amd64-s779s             2m           15Mi            
kube-proxy-l47kb                        1m           28Mi            
kube-proxy-mgc6l                        6m           16Mi            
kube-scheduler-test-1                   1m           23Mi            
kubernetes-dashboard-848b8dd798-gptsk   1m           14Mi            
metrics-server-8456fb6676-nnzcj         2m           13Mi            
tiller-deploy-7bf78cdbf7-rdm9q          1m           11Mi            

遗憾的是,当前Kubernetes Dashboard还不支持metrics-server。因此如果使用metrics-server替代了heapster,将无法在dashboard中以图形展示Pod的内存和CPU情况(实际上这也不是很重要,当前我们是在Prometheus和Grafana中定制的Kubernetes集群中各个Pod的监控,因此在dashboard中查看Pod内存和CPU也不是很重要)。 Dashboard的github上有很多这方面的讨论,如https://github.com/kubernetes/dashboard/issues/2986,Dashboard已经准备在将来的某个时间点支持metrics-server。但由于metrics-server和metrics pipeline肯定是Kubernetes在monitor方面未来的方向,所以推荐使用metrics-server。

4. 总结

本次安装涉及到的Docker镜像,如果有下载不到的请用阿里云kubernetes镜像源:registry.aliyuncs.com/google_containers

# network and dns
quay.io/coreos/flannel:v0.11.0-amd64
k8s.gcr.io/coredns:1.3.1


# helm and tiller
gcr.io/kubernetes-helm/tiller:v2.14.1

# nginx ingress
quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.24.1
k8s.gcr.io/defaultbackend:1.5

# dashboard and metric-sever
k8s.gcr.io/kubernetes-dashboard-amd64:v1.10.1
gcr.io/google_containers/metrics-server-amd64:v0.3.2

5. 参考

Installing kubeadm
Using kubeadm to Create a Cluster
Get Docker CE for CentOS
kubernetes: k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta2
k8s中文社区
使用kubeadm安装Kubernetes 1.15

Leave a Reply

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Blog Theme: FreeDom by DQF.