kubernetes-1.11.4集群部署

关闭防火墙

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

centOS 7.0版本

sudo systemctl stop firewalld.service   #停止firewall
sudo systemctl disable firewalld.service #禁止firewall开机启动
sudo firewall-cmd --state             #查看防火墙状态

禁用SELINUX

sudo setenforce 0
sudo vi /etc/selinux/config
#SELINUX修改为disabled
SELINUX=disabled 

创建/etc/sysctl.d/k8s.conf文件

sudo vi /etc/sysctl.d/k8s.conf

添加如下内容:

net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1

使修改生效,执行

sudo sysctl -p /etc/sysctl.d/k8s.conf

可能遇到问题—is an unknown key
报错

error: "net.bridge.bridge-nf-call-ip6tables" is an unknown key
error: "net.bridge.bridge-nf-call-iptables" is an unknown key

解决方法

sudo modprobe bridge
sudo lsmod |grep bridge
sudo sysctl -p /etc/sysctl.d/k8s.conf

可能遇到问题–sysctl: cannot stat /proc/sys/net/bridge/bridge-nf-call-ip6tables: 没有那个文件或目录
报错

[root@localhost ~]# sysctl -p /etc/sysctl.d/k8s.conf
sysctl: cannot stat /proc/sys/net/bridge/bridge-nf-call-ip6tables: 没有那个文件或目录
sysctl: cannot stat /proc/sys/net/bridge/bridge-nf-call-iptables: 没有那个文件或目录

解决方法

modprobe br_netfilter
ls /proc/sys/net/bridge
sudo sysctl -p /etc/sysctl.d/k8s.conf

安装Docker

安装docker的yum源:

yum install -y yum-utils device-mapper-persistent-data lvm2
yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo

使用命令:
sudo yum list docker-ce.x86_64  --showduplicates |sort -r

输出如下:

[zzq@localhost ~]$ sudo yum list docker-ce.x86_64  --showduplicates |sort -r
 * updates: mirrors.aliyun.com
Loading mirror speeds from cached hostfile
Loaded plugins: fastestmirror, priorities
 * extras: mirrors.aliyun.com
 * elrepo: mirrors.tuna.tsinghua.edu.cn
docker-ce.x86_64            18.03.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            18.03.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.12.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.12.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.09.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.09.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.2.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.06.0.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.2.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.1.ce-1.el7.centos             docker-ce-stable
docker-ce.x86_64            17.03.0.ce-1.el7.centos             docker-ce-stable
 * base: mirrors.aliyun.com
Available Packages
[zzq@localhost ~]$ 

Kubernetes 1.8已经针对Docker的1.11.2, 1.12.6, 1.13.1和17.03等版本做了验证。 因此我们这里在各节点安装docker的17.03.2版本。
使用命令如下:

sudo yum makecache fast

以及

sudo yum install -y --setopt=obsoletes=0 \
  docker-ce-17.03.2.ce-1.el7.centos \
  docker-ce-selinux-17.03.2.ce-1.el7.centos

可能遇到的问题

获取 GPG 密钥失败:[Errno 12] Timeout on https://download.docker.com/linux/centos/gpg: (28, 'Operation timed out after 30002 milliseconds with 0 out of 0 bytes received')

解决方法
一般超时原因都是网络问题,需要检查网络以及能够直接访问到这个资源比如使用命令:

curl -l https://download.docker.com/linux/centos/gpg

启动和停止docker

centOS7

sudo systemctl start docker

 

Docker从1.13版本开始调整了默认的防火墙规则,禁用了iptables filter表中FOWARD链,这样会引起Kubernetes集群中跨Node的Pod无法通信,在各个Docker节点执行下面的命令:

sudo iptables -P FORWARD ACCEPT

同时在docker的systemd unit文件中以ExecStartPost加入允许访问的代码,使用命令如下:

# 为docker服务创建一个systemd插件目录
mkdir -p /etc/systemd/system/docker.service.d
# 创建一个/etc/systemd/system/docker.service.d/port.conf配置文件
vi /etc/systemd/system/docker.service.d/port.conf

输入以下内容,保存退出:

ExecStartPost=/usr/sbin/iptables -P FORWARD ACCEPT

重启docker服务

systemctl daemon-reload
systemctl restart docker

安装kubeadm和kubelet

下面在各节点安装kubeadm和kubelet,编辑资源库

vi   /etc/yum.repos.d/kubernetes.repo

输入如下内容:

[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

安装kubernetes

yum makecache fast
yum install -y kubelet-1.11.4 kubeadm-1.11.4 kubectl-1.11.4

安装完成后输出如下:

已安装:
  kubeadm.x86_64 0:1.11.4-0                                                                               kubectl.x86_64 0:1.11.4-0                                                                               kubelet.x86_64 0:1.11.4-0                                                                              

作为依赖被安装:
  cri-tools.x86_64 0:1.11.0-0                                                                            kubernetes-cni.x86_64 0:0.6.0-0                                                                            socat.x86_64 0:1.7.3.2-2.el7    

安装结果可以看出安装的依赖和版本。
如果我们要手动安装,也可以参考相应的依赖版本。

调整启动方式

kubelet的启动环境变量要与docker的cgroup-driver驱动一样。

查看docker的cgroup-driver驱动
使用命令

docker info
或者
docker info | grep -i cgroup

输出如下:

Cgroup Driver: cgroupfs

可以看出docker 17.03使用的Cgroup Driver为cgroupfs。

Kubernetes文档中kubelet的启动参数:

--cgroup-driver string Driver that the kubelet uses to manipulate cgroups on the host.
Possible values: 'cgroupfs', 'systemd' (default "cgroupfs")

默认值为cgroupfs,yum安装kubelet,kubeadm时生成10-kubeadm.conf文件中可能将这个参数值改成了systemd。

1.11.4版本的封装在/var/lib/kubelet/kubeadm-flags.env文件中
使用命令

cat /var/lib/kubelet/kubeadm-flags.env|grep "cgroup-driver"

如果没找到则是默认的cgroupfs,不需要修改。

如果输出如下则需要修改成一致的方式,即可以修改10-kubeadm.conf中的也可以修改docker的。

KUBELET_CGROUP_ARGS=--cgroup-driver=systemd

我们这里修改各节点docker的cgroup driver使其和kubelet一致

即修改或创建/etc/docker/daemon.json
使用命令

vi /etc/docker/daemon.json

加入下面的内容:

{
  "exec-opts": ["native.cgroupdriver=systemd"]
}

重启docker:

systemctl restart docker
systemctl status docker

处理swap

Kubernetes 1.8开始要求关闭系统的Swap,如果不关闭,默认配置下kubelet将无法启动。
可以通过kubelet的启动参数–fail-swap-on=false更改这个限制。

方式一关闭swap

关闭系统的Swap方法如下:

swapoff -a

同时还需要修改/etc/fstab文件,注释掉 SWAP 的自动挂载,防止机子重启后swap启用。
使用命令

vi /etc/fstab

输出如下:

#
# /etc/fstab
# Created by anaconda on Tue Jun 19 06:52:02 2018
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=2d32a0e0-9bda-4a68-9abf-6a827a517177 /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0

注释swap这一行后保存退出

#/dev/mapper/centos-swap swap                    swap    defaults        0 0

确认swap已经关闭,使用命令

free -m

swap输出为0则说明已经关闭,如下:

[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:            976         115         283           6         577         661
Swap:             0           0           0

k8s的swappiness参数调整,修改配置文件

vi /etc/sysctl.d/k8s.conf

添加下面一行:

vm.swappiness=0

执行

sysctl -p /etc/sysctl.d/k8s.conf

使修改生效。

方式二去掉swap的限制

因为主机上还运行其他服务,关闭swap可能会对其他服务产生影响,则修改kubelet的启动参数去掉这个限制。
修改/etc/systemd/system/kubelet.service.d/10-kubeadm.conf
使用命令

vi /etc/systemd/system/kubelet.service.d/10-kubeadm.conf

加入内容:

Environment="KUBELET_EXTRA_ARGS=--fail-swap-on=false"
systemctl daemon-reload

启动kubelet服务

在各节点开机启动kubelet服务
使用命令

systemctl enable kubelet.service
systemctl start kubelet.service

准备镜像仓库

成功获取和push之后我们的镜像仓库registry.cn-qingdao.aliyuncs.com/joe-k8s/k8s中就有了相关的包。

如果没有国外的服务器节点,那我们就不能自由的定制需要的版本号镜像了。只能去找找别人已经做好的镜像仓库中有哪些版本,是否有在更新。
目前做的比较好的 持续更新的 k8s镜像仓库推荐 安家的。
Google Container Registry(gcr.io) 中国可用镜像(长期维护)
安家的github
镜像目录

这里的镜像目录https://hub.docker.com/u/anjia0532/与我们自己准备的镜像仓库registry.cn-qingdao.aliyuncs.com/joe-k8s/k8s 是同等的作用,下面会用到。

获取镜像

注意,安家的脚本因为修改过命名使用的pull.sh脚本如下:

#!/bin/bash
KUBE_VERSION=v1.11.4
KUBE_PAUSE_VERSION=3.1
ETCD_VERSION=3.2.18
DNS_VERSION=1.1.3
username=anjia0532

images=(google-containers.kube-proxy-amd64:${KUBE_VERSION}
google-containers.kube-scheduler-amd64:${KUBE_VERSION}
google-containers.kube-controller-manager-amd64:${KUBE_VERSION}
google-containers.kube-apiserver-amd64:${KUBE_VERSION}
pause:${KUBE_PAUSE_VERSION}
etcd-amd64:${ETCD_VERSION}
coredns:${DNS_VERSION}
    )

for image in ${images[@]}
do
    docker pull ${username}/${image}
    docker tag ${username}/${image} k8s.gcr.io/${image}
    #docker tag ${username}/${image} gcr.io/google_containers/${image}
    docker rmi ${username}/${image}
done

unset ARCH version images username

检查镜像
使用命令

docker images

发现已经有了需要的镜像

[root@k8s ~]# docker images
REPOSITORY                                                                 TAG                 IMAGE ID            CREATED             SIZE
k8s.gcr.io/google-containers.kube-apiserver-amd64                          v1.11.4             821507941e9c        6 days ago          187 MB
k8s.gcr.io/google-containers.kube-proxy-amd64                              v1.11.4             46a3cd725628        6 days ago          97.8 MB
k8s.gcr.io/google-containers.kube-controller-manager-amd64                 v1.11.4             38521457c799        6 days ago          155 MB
k8s.gcr.io/google-containers.kube-scheduler-amd64                          v1.11.4             37a1403e6c1a        6 days ago          56.8 MB
k8s.gcr.io/coredns                                                         1.1.3               b3b94275d97c        2 months ago        45.6 MB
k8s.gcr.io/etcd-amd64                                                      3.2.18              b8df3b177be2        4 months ago        219 MB
k8s.gcr.io/pause                                                           3.1                 da86e6ba6ca1        7 months ago        742 kB

注意 这里的前缀需要与kubeadm config images list时输出的前缀对应,否则init时仍然会识别不到去下载。
我们这里是k8s.gcr.io所以 脚本中pull 时重命名使用的是

docker tag ${username}/${image} k8s.gcr.io/${image}

如果使用的是anjia0532的版本则还需要调整一遍命名,使用命令如下:

docker tag  k8s.gcr.io/google-containers.kube-apiserver-amd64:v1.11.4   k8s.gcr.io/kube-apiserver-amd64:v1.11.4
docker tag  k8s.gcr.io/google-containers.kube-controller-manager-amd64:v1.11.4  k8s.gcr.io/kube-controller-manager-amd64:v1.11.4
docker tag  k8s.gcr.io/google-containers.kube-scheduler-amd64:v1.11.4  k8s.gcr.io/kube-scheduler-amd64:v1.11.4
docker tag k8s.gcr.io/google-containers.kube-proxy-amd64:v1.11.4   k8s.gcr.io/kube-proxy-amd64:v1.11.4

准备好的镜像如下,与kubeadm config images list时输出的镜像名称版本一致。

[root@k8s ~]# docker images
REPOSITORY                                                                 TAG                 IMAGE ID            CREATED             SIZE
k8s.gcr.io/kube-controller-manager-amd64                                   v1.11.4             38521457c799        6 days ago          155 MB
k8s.gcr.io/kube-apiserver-amd64                                            v1.11.4             821507941e9c        6 days ago          187 MB
k8s.gcr.io/kube-proxy-amd64                                                v1.11.4             46a3cd725628        6 days ago          97.8 MB
k8s.gcr.io/kube-scheduler-amd64                                            v1.11.4             37a1403e6c1a        6 days ago          56.8 MB
k8s.gcr.io/coredns                                                         1.1.3               b3b94275d97c        2 months ago        45.6 MB
k8s.gcr.io/etcd-amd64                                                      3.2.18              b8df3b177be2        4 months ago        219 MB
k8s.gcr.io/pause                                                           3.1                 da86e6ba6ca1        7 months ago        742 kB

使用kubeadm init初始化集群 (只在主节点执行)

初始化前确认 kubelet启动和 cgroup-driver等方式是否对应。

接下来使用kubeadm初始化集群,选择k8s作为Master Node
确保没有设置http_proxy和https_proxy代理
在k8s上执行下面的命令:

kubeadm init   --kubernetes-version=v1.11.4   --pod-network-cidr=10.244.0.0/16   --apiserver-advertise-address=192.168.11.90 --token-ttl 0

–kubernetes-version根据上面安装成功时的提示:kubectl.x86_64 0:1.11.4-0对应版本。
因为我们选择flannel作为Pod网络插件,所以上面的命令指定–pod-network-cidr=10.244.0.0/16。
对于某些网络解决方案,Kubernetes master 也可以为每个节点分配网络范围(CIDR),这包括一些云提供商和 flannel。通过 –pod-network-cidr 参数指定的子网范围将被分解并发送给每个 node。这个范围应该使用最小的 /16,以让 controller-manager 能够给集群中的每个 node 分配 /24 的子网。如果我们是通过 这个 manifest 文件来使用 flannel,那么您应该使用 –pod-network-cidr=10.244.0.0/16。大部分基于 CNI 的网络解决方案都不需要这个参数。
–apiserver-advertise-address是apiserver的通信地址,一般使用master的ip地址。

通过kubeadm初始化后,都会提供节点加入k8s集群的token。默认token的有效期为24小时,当过期之后,该token就不可用了,需要重新生成token,会比较麻烦,这里–token-ttl设置为0表示永不过期。
token过期后重新创建token的方法看文末。

可能遇到的问题-卡在preflight/images

init过程中kubernetes会自动从google服务器中下载相关的docker镜像
kubeadm init过程首先会检查代理服务器,确定跟 kube-apiserver 的 https 连接方式,如果有代理设置,会提出警告。
如果一直卡在preflight/images

[preflight/images] Pulling images required for setting up a Kubernetes cluster
[preflight/images] This might take a minute or two, depending on the speed of your internet connection
[preflight/images] You can also perform this action in beforehand using 'kubeadm config images pull'

请查看上一小节,先准备相关镜像。

可能遇到的问题-uses proxy

如果报错

    [WARNING HTTPProxy]: Connection to "https://192.168.11.90" uses proxy "http://127.0.0.1:8118". If that is not intended, adjust your proxy settings
    [WARNING HTTPProxyCIDR]: connection to "10.96.0.0/12" uses proxy "http://127.0.0.1:8118". This may lead to malfunctional cluster setup. Make sure that Pod and Services IP ranges specified correctly as exceptions in proxy configuration
    [WARNING HTTPProxyCIDR]: connection to "10.244.0.0/16" uses proxy "http://127.0.0.1:8118". This may lead to malfunctional cluster setup. Make sure that Pod and Services IP ranges specified correctly as exceptions in proxy configuration

则设置no_proxy
使用命令

vi /etc/profile

在最后添加

export no_proxy='anjia0532,127.0.0.1,192.168.11.90,k8s.gcr.io,10.96.0.0/12,10.244.0.0/16'

使用命令让配置生效

source /etc/profile

更多init的错误可以新开一个控制台使用命令跟踪:

journalctl -f -u kubelet.service

可以查看具体的卡住原因。

可能遇到的问题-failed to read kubelet config file “/var/lib/kubelet/config.yaml”

8月 14 20:44:42 k8s systemd[1]: kubelet.service holdoff time over, scheduling restart.
8月 14 20:44:42 k8s systemd[1]: Started kubelet: The Kubernetes Node Agent.
8月 14 20:44:42 k8s systemd[1]: Starting kubelet: The Kubernetes Node Agent...
8月 14 20:44:42 k8s kubelet[5471]: F0814 20:44:42.477878    5471 server.go:190] failed to load Kubelet config file /var/lib/kubelet/config.yaml, error failed to read kubelet config file "/var/lib/kubelet/config.yaml", error: open /var/lib/kubelet/config.yaml: no such file or directory

原因
关键文件缺失,多发生于没有做 kubeadm init就运行了systemctl start kubelet。
解决方法
先成功运行kubeadm init。

可能遇到的问题–cni config uninitialized

KubeletNotReady runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized

原因
因为kubelet配置了network-plugin=cni,但是还没安装,所以状态会是NotReady,不想看这个报错或者不需要网络,就可以修改kubelet配置文件,去掉network-plugin=cni 就可以了。
解决方法

vi /etc/systemd/system/kubelet.service.d/10-kubeadm.conf

删除最后一行里的$KUBELET_NETWORK_ARGS
1.11.4版本的封装在/var/lib/kubelet/kubeadm-flags.env文件中
使用命令

[root@k8s ~]# cat /var/lib/kubelet/kubeadm-flags.env
KUBELET_KUBEADM_ARGS=--cgroup-driver=systemd --cni-bin-dir=/opt/cni/bin --cni-conf-dir=/etc/cni/net.d --network-plugin=cni

重启kubelet

systemctl enable kubelet && systemctl start kubelet

重新初始化

kubeadm reset 
kubeadm init   --kubernetes-version=v1.11.4   --pod-network-cidr=10.244.0.0/16   --apiserver-advertise-address=192.168.11.90 --token-ttl 0

正确初始化输出如下:

[root@k8s ~]# kubeadm init   --kubernetes-version=v1.11.4   --pod-network-cidr=10.244.0.0/16   --apiserver-advertise-address=192.168.11.90 --token-ttl 0
[init] using Kubernetes version: v1.11.4
[preflight] running pre-flight checks
I0815 16:24:34.651252   21183 kernel_validator.go:81] Validating kernel version
I0815 16:24:34.651356   21183 kernel_validator.go:96] Validating kernel config
[preflight/images] Pulling images required for setting up a Kubernetes cluster
[preflight/images] This might take a minute or two, depending on the speed of your internet connection
[preflight/images] You can also perform this action in beforehand using 'kubeadm config images pull'
[kubelet] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[preflight] Activating the kubelet service
[certificates] Generated ca certificate and key.
[certificates] Generated apiserver certificate and key.
[certificates] apiserver serving cert is signed for DNS names [k8s kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.11.90]
[certificates] Generated apiserver-kubelet-client certificate and key.
[certificates] Generated sa key and public key.
[certificates] Generated front-proxy-ca certificate and key.
[certificates] Generated front-proxy-client certificate and key.
[certificates] Generated etcd/ca certificate and key.
[certificates] Generated etcd/server certificate and key.
[certificates] etcd/server serving cert is signed for DNS names [k8s localhost] and IPs [127.0.0.1 ::1]
[certificates] Generated etcd/peer certificate and key.
[certificates] etcd/peer serving cert is signed for DNS names [k8s localhost] and IPs [192.168.11.90 127.0.0.1 ::1]
[certificates] Generated etcd/healthcheck-client certificate and key.
[certificates] Generated apiserver-etcd-client certificate and key.
[certificates] valid certificates and keys now exist in "/etc/kubernetes/pki"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/admin.conf"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/kubelet.conf"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/controller-manager.conf"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/scheduler.conf"
[controlplane] wrote Static Pod manifest for component kube-apiserver to "/etc/kubernetes/manifests/kube-apiserver.yaml"
[controlplane] wrote Static Pod manifest for component kube-controller-manager to "/etc/kubernetes/manifests/kube-controller-manager.yaml"
[controlplane] wrote Static Pod manifest for component kube-scheduler to "/etc/kubernetes/manifests/kube-scheduler.yaml"
[etcd] Wrote Static Pod manifest for a local etcd instance to "/etc/kubernetes/manifests/etcd.yaml"
[init] waiting for the kubelet to boot up the control plane as Static Pods from directory "/etc/kubernetes/manifests" 
[init] this might take a minute or longer if the control plane images have to be pulled
[apiclient] All control plane components are healthy after 40.004083 seconds
[uploadconfig] storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.11" in namespace kube-system with the configuration for the kubelets in the cluster
[markmaster] Marking the node k8s as master by adding the label "node-role.kubernetes.io/master=''"
[markmaster] Marking the node k8s as master by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "k8s" as an annotation
[bootstraptoken] using token: hu2clf.898he8fnu64w3fur
[bootstraptoken] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstraptoken] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstraptoken] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstraptoken] creating the "cluster-info" ConfigMap in the "kube-public" namespace
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your Kubernetes master 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/

You can now join any number of machines by running the following on each node
as root:

  kubeadm join 192.168.11.90:6443 --token hu2clf.898he8fnu64w3fur --discovery-token-ca-cert-hash sha256:2a196bbd77e4152a700d294a666e9d97336d0f7097f55e19a651c19e03d340a4

上面记录了完成的初始化输出的内容。

其中有以下关键内容:
生成token记录下来,后边使用kubeadm join往集群中添加节点时会用到
下面的命令是配置常规用户如何使用kubectl(客户端)访问集群,因为master节点也需要使用kubectl访问集群,所以也需要运行以下命令:

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

最后给出了将节点加入集群的命令

kubeadm join 192.168.11.90:6443 --token hu2clf.898he8fnu64w3fur --discovery-token-ca-cert-hash sha256:2a196bbd77e4152a700d294a666e9d97336d0f7097f55e19a651c19e03d340a4

查看一下集群状态如下:

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

确认每个组件都处于healthy状态。

可能遇到的问题–net/http: TLS handshake timeout

如果报错主节点的6443端口无法连接,超时,拒绝连接。需要检查网络,一般来说 是因我们我们设置了http_proxy和https_proxy做代理翻墙导致不能访问自身和内网。
需要在/etc/profile中增加no_proxy参数后重试,或者重新init。
如下:

vi /etc/profile

在最后增加

export no_proxy='anjia0532,127.0.0.1,192.168.11.90,192.168.11.91,192.168.11.92,k8s.gcr.io,10.96.0.0/12,10.244.0.0/16,localhost'

保存退出。
让配置生效

source /etc/profile

如果仍然无效,重新init,因为init时会帮助我们去检查网络情况,一般init时没有警告是没问题的。
使用命令:

kubeadm reset
kubeadm init

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

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

安装Pod Network (只在主节点执行)

接下来安装flannel network add-on:

mkdir -p ~/k8s/
cd ~/k8s
wget 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

这里可以cat查看kube-flannel.yml这个文件里的flannel的镜像的版本

cat kube-flannel.yml|grep quay.io/coreos/flannel

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

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

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

[root@k8s k8s]# kubectl get pod --all-namespaces -o wide
NAMESPACE     NAME                          READY     STATUS    RESTARTS   AGE       IP              NODE      NOMINATED NODE
kube-system   coredns-78fcdf6894-jf5tn      1/1       Running   0          6m        10.244.0.3      k8s       <none>
kube-system   coredns-78fcdf6894-ljmmh      1/1       Running   0          6m        10.244.0.2      k8s       <none>
kube-system   etcd-k8s                      1/1       Running   0          5m        192.168.11.90   k8s       <none>
kube-system   kube-apiserver-k8s            1/1       Running   0          5m        192.168.11.90   k8s       <none>
kube-system   kube-controller-manager-k8s   1/1       Running   0          5m        192.168.11.90   k8s       <none>
kube-system   kube-flannel-ds-amd64-fvpj7   1/1       Running   0          4m        192.168.11.90   k8s       <none>
kube-system   kube-proxy-c8rrg              1/1       Running   0          6m        192.168.11.90   k8s       <none>
kube-system   kube-scheduler-k8s            1/1       Running   0          5m        192.168.11.90   k8s       <none>

master node参与工作负载 (只在主节点执行)

使用kubeadm初始化的集群,出于安全考虑Pod不会被调度到Master Node上,也就是说Master Node不参与工作负载。

这里搭建的是测试环境可以使用下面的命令使Master Node参与工作负载:
k8s是master节点的hostname
允许master节点部署pod,使用命令如下:

kubectl taint nodes --all node-role.kubernetes.io/master-

输出如下:

node "k8s" untainted

输出error: taint “node-role.kubernetes.io/master:” not found错误忽略。

禁止master部署pod

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

测试DNS (只在主节点执行)

使用命令

kubectl run curl --image=radial/busyboxplus:curl -i --tty

输出如下:

If you don't see a command prompt, try pressing enter.
[ root@curl-87b54756-vsf2s:/ ]$ 

进入后执行

nslookup kubernetes.default

确认解析正常,输出如下:

[ root@curl-87b54756-vsf2s:/ ]$ 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

输入

exit;

可退出image。

向Kubernetes集群添加Node (只在副节点执行)

下面我们将k8s1这个主机添加到Kubernetes集群中,在k8s1上执行之前的加入语句:

kubeadm join 192.168.11.90:6443 --token hu2clf.898he8fnu64w3fur --discovery-token-ca-cert-hash sha256:2a196bbd77e4152a700d294a666e9d97336d0f7097f55e19a651c19e03d340a4

正确加入输出如下:

[root@k8s1 ~]# kubeadm join 192.168.11.90:6443 --token hu2clf.898he8fnu64w3fur --discovery-token-ca-cert-hash sha256:2a196bbd77e4152a700d294a666e9d97336d0f7097f55e19a651c19e03d340a4
[preflight] running pre-flight checks
    [WARNING RequiredIPVSKernelModulesAvailable]: the IPVS proxier will not be used, because the following required kernel modules are not loaded: [ip_vs ip_vs_rr ip_vs_wrr ip_vs_sh] or no builtin kernel ipvs support: map[ip_vs:{} ip_vs_rr:{} ip_vs_wrr:{} ip_vs_sh:{} nf_conntrack_ipv4:{}]
you can solve this problem with following methods:
 1. Run 'modprobe -- ' to load missing kernel modules;
2. Provide the missing builtin kernel ipvs support

I0815 16:53:55.675009    2758 kernel_validator.go:81] Validating kernel version
I0815 16:53:55.675090    2758 kernel_validator.go:96] Validating kernel config
[discovery] Trying to connect to API Server "192.168.11.90:6443"
[discovery] Created cluster-info discovery client, requesting info from "https://192.168.11.90:6443"
[discovery] Requesting info from "https://192.168.11.90:6443" again to validate TLS against the pinned public key
[discovery] Cluster info signature and contents are valid and TLS certificate validates against pinned roots, will use API Server "192.168.11.90:6443"
[discovery] Successfully established connection with API Server "192.168.11.90:6443"
[kubelet] Downloading configuration for the kubelet from the "kubelet-config-1.11" ConfigMap in the kube-system namespace
[kubelet] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[preflight] Activating the kubelet service
[tlsbootstrap] Waiting for the kubelet to perform the TLS Bootstrap...
[patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "k8s1" as an annotation

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

Run 'kubectl get nodes' on the master to see this node join the cluster.

下面在master节点上执行命令查看集群中的节点:

[root@k8s k8s]# kubectl get nodes
NAME      STATUS     ROLES     AGE       VERSION
k8s       Ready      master    30m       v1.11.4
k8s1      NotReady   <none>    1m        v1.11.4
k8s2      NotReady   <none>    1m        v1.11.4
[root@k8s k8s]# 

如果副节点是NotReady,可以使用命令检查是否有报错

systemctl status kubelet.service

使用命令检查pod是否是running状态

[root@k8s kubernetes]# kubectl get pod --all-namespaces -o wide
NAMESPACE     NAME                          READY     STATUS              RESTARTS   AGE       IP              NODE      NOMINATED NODE
default       curl-87b54756-vsf2s           1/1       Running             1          1h        10.244.0.4      k8s       <none>
kube-system   coredns-78fcdf6894-jf5tn      1/1       Running             0          2h        10.244.0.3      k8s       <none>
kube-system   coredns-78fcdf6894-ljmmh      1/1       Running             0          2h        10.244.0.2      k8s       <none>
kube-system   etcd-k8s                      1/1       Running             0          2h        192.168.11.90   k8s       <none>
kube-system   kube-apiserver-k8s            1/1       Running             0          2h        192.168.11.90   k8s       <none>
kube-system   kube-controller-manager-k8s   1/1       Running             0          2h        192.168.11.90   k8s       <none>
kube-system   kube-flannel-ds-amd64-8p2px   0/1       Init:0/1            0          1h        192.168.11.91   k8s1      <none>
kube-system   kube-flannel-ds-amd64-fvpj7   1/1       Running             0          2h        192.168.11.90   k8s       <none>
kube-system   kube-flannel-ds-amd64-p6g4w   0/1       Init:0/1            0          1h        192.168.11.92   k8s2      <none>
kube-system   kube-proxy-c8rrg              1/1       Running             0          2h        192.168.11.90   k8s       <none>
kube-system   kube-proxy-hp4lj              0/1       ContainerCreating   0          1h        192.168.11.92   k8s2      <none>
kube-system   kube-proxy-tn2fl              0/1       ContainerCreating   0          1h        192.168.11.91   k8s1      <none>
kube-system   kube-scheduler-k8s            1/1       Running             0          2h        192.168.11.90   k8s       <none>

如果卡在ContainerCreating状态和Init:0/1一般也是副节点的镜像获取不到的问题,请回到 准备镜像小节。
准备好镜像之后一般很快就会变成running状态如下:

[root@k8s kubernetes]# kubectl get pod --all-namespaces -o wide
NAMESPACE     NAME                          READY     STATUS    RESTARTS   AGE       IP              NODE      NOMINATED NODE
default       curl-87b54756-vsf2s           1/1       Running   1          1h        10.244.0.4      k8s       <none>
kube-system   coredns-78fcdf6894-jf5tn      1/1       Running   0          2h        10.244.0.3      k8s       <none>
kube-system   coredns-78fcdf6894-ljmmh      1/1       Running   0          2h        10.244.0.2      k8s       <none>
kube-system   etcd-k8s                      1/1       Running   0          2h        192.168.11.90   k8s       <none>
kube-system   kube-apiserver-k8s            1/1       Running   0          2h        192.168.11.90   k8s       <none>
kube-system   kube-controller-manager-k8s   1/1       Running   0          2h        192.168.11.90   k8s       <none>
kube-system   kube-flannel-ds-amd64-8p2px   1/1       Running   0          1h        192.168.11.91   k8s1      <none>
kube-system   kube-flannel-ds-amd64-fvpj7   1/1       Running   0          2h        192.168.11.90   k8s       <none>
kube-system   kube-flannel-ds-amd64-p6g4w   1/1       Running   0          1h        192.168.11.92   k8s2      <none>
kube-system   kube-proxy-c8rrg              1/1       Running   0          2h        192.168.11.90   k8s       <none>
kube-system   kube-proxy-hp4lj              1/1       Running   0          1h        192.168.11.92   k8s2      <none>
kube-system   kube-proxy-tn2fl              1/1       Running   0          1h        192.168.11.91   k8s1      <none>
kube-system   kube-scheduler-k8s            1/1       Running   0          2h        192.168.11.90   k8s       <none>

此时查看nodes也已经变成了ready状态

[root@k8s kubernetes]# kubectl get nodes
NAME      STATUS    ROLES     AGE       VERSION
k8s       Ready     master    2h        v1.11.4
k8s1      Ready     <none>    1h        v1.11.4
k8s2      Ready     <none>    1h        v1.11.4
[root@k8s kubernetes]# 

如果副节点也需要使用kubectl命令则需要把conf文件复制过去,使用命令

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

如何从集群中移除Node

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

在master节点上执行:

kubectl drain k8s2 --delete-local-data --force --ignore-daemonsets
kubectl delete node k8s2

在k8s2上执行:

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

到这里我们就算成功安装好了k8s集群了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值