docker容器化部署kubeadmin --1.18版

Kubernetes概述

简介
Kubernetes是一个开源的,用于管理云平台中多个主机上的容器化的应用,Kubernetes的目标是让部署容器化的应用简单并且高效(powerful),Kubernetes提供了应用部署,规划,更新,维护的一种机制。

Kubernetes一个核心的特点就是能够自主的管理容器来保证云平台中的容器按照用户的期望状态运行着(比如用户想让apache一直运行,用户不需要关心怎么去做,Kubernetes会自动去监控,然后去重启,新建,总之,让apache一直提供服务),管理员可以加载一个微型服务,让规划器来找到合适的位置,同时,Kubernetes也系统提升工具以及人性化方面,让用户能够方便的部署自己的应用(就像canary deployments)。

现在Kubernetes着重于不间断的服务状态(比如web服务器或者缓存服务器)和原生云平台应用(Nosql),在不久的将来会支持各种生产云平台中的各种服务,例如,分批,工作流,以及传统数据库。

在Kubenetes中,所有的容器均在Pod中运行,一个Pod可以承载一个或者多个相关的容器,在后边的案例中,同一个Pod中的容器会部署在同一个物理机器上并且能够共享资源。一个Pod也可以包含O个或者多个磁盘卷组(volumes),这些卷组将会以目录的形式提供给一个容器,或者被所有Pod中的容器共享,对于用户创建的每个Pod,系统会自动选择那个健康并且有足够容量的机器,然后创建类似容器的容器,当容器创建失败的时候,容器会被node agent自动的重启,这个node agent叫kubelet,但是,如果是Pod失败或者机器,它不会自动的转移并且启动,除非用户定义了 replication controller。

用户可以自己创建并管理Pod,Kubernetes将这些操作简化为两个操作:基于相同的Pod配置文件部署多个Pod复制品;创建可替代的Pod当一个Pod挂了或者机器挂了的时候。而Kubernetes API中负责来重新启动,迁移等行为的部分叫做“replication controller”,它根据一个模板生成了一个Pod,然后系统就根据用户的需求创建了许多冗余,这些冗余的Pod组成了一个整个应用,或者服务,或者服务中的一层。一旦一个Pod被创建,系统就会不停的监控Pod的健康情况以及Pod所在主机的健康情况,如果这个Pod因为软件原因挂掉了或者所在的机器挂掉了,replication controller 会自动在一个健康的机器上创建一个一摸一样的Pod,来维持原来的Pod冗余状态不变,一个应用的多个Pod可以共享一个机器。

我们经常需要选中一组Pod,例如,我们要限制一组Pod的某些操作,或者查询某组Pod的状态,作为Kubernetes的基本机制,用户可以给Kubernetes Api中的任何对象贴上一组 key:value的标签,然后,我们就可以通过标签来选择一组相关的Kubernetes Api 对象,然后去执行一些特定的操作,每个资源额外拥有一组(很多) keys 和 values,然后外部的工具可以使用这些keys和vlues值进行对象的检索,这些Map叫做annotations(注释)。

Kubernetes支持一种特殊的网络模型,Kubernetes创建了一个地址空间,并且不动态的分配端口,它可以允许用户选择任何想使用的端口,为了实现这个功能,它为每个Pod分配IP地址。

现代互联网应用一般都会包含多层服务构成,比如web前台空间与用来存储键值对的内存服务器以及对应的存储服务,为了更好的服务于这样的架构,Kubernetes提供了服务的抽象,并提供了固定的IP地址和DNS名称,而这些与一系列Pod进行动态关联,这些都通过之前提到的标签进行关联,所以我们可以关联任何我们想关联的Pod,当一个Pod中的容器访问这个地址的时候,这个请求会被转发到本地代理(kube proxy),每台机器上均有一个本地代理,然后被转发到相应的后端容器。Kubernetes通过一种轮训机制选择相应的后端容器,这些动态的Pod被替换的时候,Kube proxy时刻追踪着,所以,服务的 IP地址(dns名称),从来不变。

所有Kubernetes中的资源,比如Pod,都通过一个叫URI的东西来区分,这个URI有一个UID,URI的重要组成部分是:对象的类型(比如pod),对象的名字,对象的命名空间,对于特殊的对象类型,在同一个命名空间内,所有的名字都是不同的,在对象只提供名称,不提供命名空间的情况下,这种情况是假定是默认的命名空间。UID是时间和空间上的唯一。

起源
大规模容器集群管理工具,从Borg到Kubernetes

在Docker 作为高级容器引擎快速发展的同时,Google也开始将自身在容器技术及集群方面的积累贡献出来。在Google内部,容器技术已经应用了很多年,Borg系统运行管理着成千上万的容器应用,在它的支持下,无论是谷歌搜索、Gmail还是谷歌地图,可以轻而易举地从庞大的数据中心中获取技术资源来支撑服务运行。

Borg是集群的管理器,在它的系统中,运行着众多集群,而每个集群可由成千上万的服务器联接组成,Borg每时每刻都在处理来自众多应用程序所提交的成百上千的Job, 对这些Job进行接收、调度、启动、停止、重启和监控。正如Borg论文中所说,Borg提供了3大好处:

1)隐藏资源管理和错误处理,用户仅需要关注应用的开发。

  1. 服务高可用、高可靠。

  2. 可将负载运行在由成千上万的机器联合而成的集群中。

作为Google的竞争技术优势,Borg理所当然的被视为商业秘密隐藏起来,但当Tiwtter的工程师精心打造出属于自己的Borg系统(Mesos)时, Google也审时度势地推出了来源于自身技术理论的新的开源工具。

2014年6月,谷歌云计算专家埃里克·布鲁尔(Eric Brewer)在旧金山的发布会为这款新的开源工具揭牌,它的名字Kubernetes在希腊语中意思是船长或领航员,这也恰好与它在容器集群管理中的作用吻合,即作为装载了集装箱(Container)的众多货船的指挥者,负担着全局调度和运行监控的职责。

虽然Google推出Kubernetes的目的之一是推广其周边的计算引擎(Google Compute Engine)和谷歌应用引擎(Google App Engine)。但Kubernetes的出现能让更多的互联网企业可以享受到连接众多计算机成为集群资源池的好处。

Kubernetes对计算资源进行了更高层次的抽象,通过将容器进行细致的组合,将最终的应用服务交给用户。Kubernetes在模型建立之初就考虑了容器跨机连接的要求,支持多种网络解决方案,同时在Service层次构建集群范围的SDN网络。其目的是将服务发现和负载均衡放置到容器可达的范围,这种透明的方式便利了各个服务间的通信,并为微服务架构的实践提供了平台基础。而在Pod层次上,作为Kubernetes可操作的最小对象,其特征更是对微服务架构的原生支持。

Kubernetes项目来源于Borg,可以说是集结了Borg设计思想的精华,并且吸收了Borg系统中的经验和教训。

Kubernetes作为容器集群管理工具,于2015年7月22日迭代到 v 1.0并正式对外公布,这意味着这个开源容器编排系统可以正式在生产环境使用。与此同时,谷歌联合Linux基金会及其他合作伙伴共同成立了CNCF基金会( Cloud Native Computing Foundation),并将Kuberentes 作为首个编入CNCF管理体系的开源项目,助力容器技术生态的发展进步。Kubernetes项目凝结了Google过去十年间在生产环境的经验和教训,从Borg的多任务Alloc资源块到Kubernetes的多副本Pod,从Borg的Cell集群管理,到Kubernetes设计理念中的联邦集群,在Docker等高级引擎带动容器技术兴起和大众化的同时,为容器集群管理提供独了到见解和新思路。

kubeadm 概述
Kubeadm 是一个工具,它提供了 kubeadm init 以及 kubeadm join 这两个命令作为快速创建 kubernetes 集群的最佳实践。
kubeadm 通过执行必要的操作来启动和运行一个最小可用的集群。它被故意设计为只关心启动集群,而不是准备节点环境的工作。同样的,诸如安装各种各样的可有可无的插件,例如 Kubernetes 控制面板、监控解决方案以及特定云提供商的插件,这些都不在它负责的范围。

相反,我们期望由一个基于 kubeadm 从更高层设计的更加合适的工具来做这些事情;并且,理想情况下,使用 kubeadm 作为所有部署的基础将会使得创建一个符合期望的集群变得容易。

一. 环境准备

地址规划

准备设备2台
192.168.100.20 K8S-m01 master
192.168.100.21 K8S-m02 node

修改主机名

[root@pc-20 ~]# hostnamectl  set-hostname k8s-m1
[root@pc-20 ~]# su
[root@k8s-m1 ~]#

[root@pc-21 ~]# hostnamectl set-hostname k8s-m2
[root@pc-21 ~]# su
[root@k8s-m2 ~]#

设置hosts

cat>>/etc/hosts<<\EOF 
192.168.100.20  k8s-m01 
192.168.100.21  k8s-m02 
EOF

设置时钟同步计划任务

root@k8s-m2 ~]# yum install ntpdate -y

[root@k8s-m2 ~]# echo "*/5* * * * /usr/sbin/ntpdate ntp1.aliyun.com >/dev/null 2>&1" >>/var/spool/cron/root

[root@k8s-m2 ~]# crontab -l
*/5* * * * /usr/sbin/ntpdate ntp1.aliyun.com >/dev/null 2>&1

优化内核参数

[root@k8s-m2 ~]# cat >/etc/sysctl.d/kubernetes.conf<<\EOF

net.bridge.bridge-nf-call-iptables=1
net.bridge.bridge-nf-call-ip6tables=1
net.ipv4.ip_forward=1
net.ipv4.tcp_tw_recycle=0
vm.swappiness=0
vm.overcommit_memory=1
vm.panic_on_oom=0
fs.inotify.max_user_instances=8192
fs.inotify.max_user_watches=1048576
fs.file-max=52706963
fs.nr_open=52706963
net.ipv6.conf.all.disable_ipv6=1
net.netfilter.nf_conntrack_max=2310720
EOF

[root@k8s-m2 ~]# modprobe ip_vs_rr
[root@k8s-m2 ~]# modprobe br_netfilter
[root@k8s-m2 ~]# sysctl -p /etc/sysctl.d/kubernetes.conf
net.bridge.bridge-nf-call-iptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.ipv4.ip_forward = 1
net.ipv4.tcp_tw_recycle = 0
vm.swappiness = 0
vm.overcommit_memory = 1
vm.panic_on_oom = 0
fs.inotify.max_user_instances = 8192
fs.inotify.max_user_watches = 1048576
fs.file-max = 52706963
fs.nr_open = 52706963
net.ipv6.conf.all.disable_ipv6 = 1
net.netfilter.nf_conntrack_max = 2310720
[root@k8s-m2 ~]#

注:
tcp _tw. recycle和Kubernetes的NAT冲突,必须关闭, 否则会导致服务不通;
关闭不使用的IPV6协议栈,防止触发docker BUG ;

关闭swap分区

如果开启了swap分区, kubelet会启动失败(可以通过将参数-ail-swap-on设置为false来忽略swap on) ,故需要在每个node节点机器上关团swap分区。
swapoff -a 
sed -ri 's/.*swap.*/#&/' /etc/fstab

关闭防火墙和selinux

[root@k8s-m2 ~]# systemctl stop firewalld
[root@k8s-m2 ~]# systemctl disable firewalld
[root@k8s-m2 ~]# iptables -F && iptables -X && iptables -F -t nat && iptables -X -t nat[root@k8s-m2 ~]# iptables -P FORWARD ACCEPT
[root@k8s-m2 ~]# setenforce 0
setenforce: SELinux is disabled
[root@k8s-m2 ~]# sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config

安装docker

yum -y install yum-utils device-mapper-persistent-data lvm2

[root@k8s-m1 ~]# wget -P /etc/yum.repos.d/ https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

Yum makecache
yum -y install docker-ce-18.06.3.ce

创建docker 目录

[root@k8s-m1 ~]# mkdir -p /etc/docker

创建镜像加速文件

[root@k8s-m1 ~]# cat> /etc/docker/daemon.json<<\EOF

{
“registry-mirrors”: [“https://q3u0qv3z.mirror.aliyuncs.com”]
}
EOF
[root@k8s-m1 ~]#

systemctl daemon-reload  #重新载入
 systemctl restart docker   #启动
 systemctl enable docker  #开机自启

升级内核

升级内核
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
yum --enablerepo=elrepo-kernel install kernel-lt -y
grub2-set-default 0 && grub2-mkconfig -o /etc/grub2.cfg
reboot #重启服务器

二,Kubeadm部署集群

1,安装kubeadm,kubelet,kubectl

所有节点都安装kubeadm,kubelet,kubectl,但是:node节点上的kubectl不是必须的。
● kubeadm:集群管理命令。
● kubelet: 该组件运行在集群中所有机器上,执行启动pod和容器等操作。
● kubectl:与集群通信的命令工具。
kubeadm不会为你安装或管理kubelet或kubectl ,因此你需要确保它们与kubeadm安装的Kubernetes控制平面版本匹配。否则,就有发生版本倾斜的风险,这可能导致意外的错误行为。然而, kubelet和控制平面之间的一个小版本倾斜是允许的,但是kubelet版本可能永远不会超过API服务器版本。例如,运行1.7.0的kubelets应该完全兼容1.8.0 API服务器,反之则不然。

配置安装源(都需要)

[root@k8s-m1 ~]# cat <<EOF > /etc/yum.repos.d/kubernetes.repo
 [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.gpghttps://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
 EOF
[root@k8s-m1 ~]#

清除和重载缓存

yum clean all 
yum makecache

安装指定的版本

yum install -y kubelet-1.18.0 kubeadm-1.18.0 kubectl-1.18.0
systemctl enable --now kubelet #开机自启

配置初始化master

2.1,获取默认配置文件

[root@ k8s-m01 ~]# kubeadm init --config kubeadm-init.yaml

2.2,修改配置文件

root@ k8s-m01 ~] vim kubeadm-init.yaml

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: 192.168.100.20           //宿主机IP地址
  bindPort: 6443
nodeRegistration:
  criSocket: /var/run/dockershim.sock
  name: k8s-m01
  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.18.0
networking:
  dnsDomain: cluster.local
  podSubnet: "10.244.0.0/16"         //#网络插件flannel的默认网络地址
  serviceSubnet: 10.96.0.0/12
scheduler: {}

3,在两台服务器上拉取k8s镜像

[root@k8s-m2 ~]# cat >k8s.images<<EOF
 kube-apiserver:v1.18.0
kube-controller-manager:v1.18.0
 kube-proxy:v1.18.0
 kube-scheduler:v1.18.0
 coredns:1.6.7
 etcd:3.4.3-0
 pause:3.2
EOF
[root@k8s-m2 ~]# for i in `cat k8s.images`
do
   REPO=$(echo "$i"|awk -F ':' '{print $1}')
   TAG=$(echo "$i"|awk -F ':' '{print $2}')
    sudo docker pull registry.cn-beijing.aliyuncs.com/crazywjj/$i
    sudo docker tag  registry.cn-beijing.aliyuncs.com/crazywjj/$i k8s.gcr.io/$REPO:$TAG
   sudo docker rmi -f registry.cn-beijing.aliyuncs.com/crazywjj/$i
 done

初始化master

kubeadm init --config kubeadm-init.yaml



[root@k8s-m01 ~]# kubeadm init --config kubeadm-init.yaml
W1031 13:00:52.739237   45775 configset.go:202] WARNING: kubeadm cannot validate component configs for API groups [kubelet.config.k8s.io kubeproxy.config.k8s.io]
[init] Using Kubernetes version: v1.18.0
[preflight] Running pre-flight checks
	[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/
[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] Starting the kubelet
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Using existing ca certificate authority
[certs] Using existing apiserver certificate and key on disk
[certs] Using existing apiserver-kubelet-client certificate and key on disk
[certs] Using existing front-proxy-ca certificate authority
[certs] Using existing front-proxy-client certificate and key on disk
[certs] Using existing etcd/ca certificate authority
[certs] Using existing etcd/server certificate and key on disk
[certs] Using existing etcd/peer certificate and key on disk
[certs] Using existing etcd/healthcheck-client certificate and key on disk
[certs] Using existing apiserver-etcd-client certificate and key on disk
[certs] Using the existing "sa" key
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[kubeconfig] Using existing kubeconfig file: "/etc/kubernetes/admin.conf"
[kubeconfig] Using existing kubeconfig file: "/etc/kubernetes/kubelet.conf"
[kubeconfig] Using existing kubeconfig file: "/etc/kubernetes/controller-manager.conf"
[kubeconfig] Using existing kubeconfig file: "/etc/kubernetes/scheduler.conf"
[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"
W1031 13:00:53.930060   45775 manifests.go:225] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[control-plane] Creating static Pod manifest for "kube-scheduler"
W1031 13:00:53.930874   45775 manifests.go:225] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[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 4.503118 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.18" 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 k8s-m01 as control-plane by adding the label "node-role.kubernetes.io/master=''"
[mark-control-plane] Marking the node k8s-m01 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 192.168.100.20:6443 --token abcdef.0123456789abcdef \
    --discovery-token-ca-cert-hash sha256:5c452f5eaee37c6ae331878e524cda7b67dc466909100df91b73cd007e97d35c
[root@k8s-m01 ~]#

配置kubectl命令

[root@k8s-m01 ~]# mkdir -p $HOME/.kube
[root@k8s-m01 ~]# sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
[root@k8s-m01 ~]# sudo chown $(id -u):$(id -g) $HOME/.kube/config
[root@k8s-m01 ~]#

获取pods列表命令

[root@ k8s-m01 ~] # yum install -y bash-completion
[root@k8s-m01 ~]# echo 'source /usr/share/bash-completion/bash_completion' >> /etc/profile
[root@k8s-m01 ~]# source /etc/profile
[root@k8s-m01 ~]# source <(kubectl completion bash)
[root@k8s-m01 ~]# echo "source <(kubectl completion bash)" >> ~/.bashrc
[root@k8s-m01 ~]# source ~/.bashrc

查看pod

[root@k8s-m01 ~]# kubectl get pods --all-namespaces
NAMESPACE     NAME                              READY   STATUS    RESTARTS   AGE
kube-system   coredns-66bff467f8-h878c          0/1     Pending   0          4m59s
kube-system   coredns-66bff467f8-jb6xs          0/1     Pending   0          4m59s
kube-system   etcd-k8s-m01                      1/1     Running   79         5m16s
kube-system   kube-apiserver-k8s-m01            1/1     Running   57         5m16s
kube-system   kube-controller-manager-k8s-m01   1/1     Running   4          5m16s
kube-system   kube-proxy-55b6q                  1/1     Running   0          4m59s
kube-system   kube-scheduler-k8s-m01            1/1     Running   4          5m16s

查看群集健康

[root@k8s-m01 ~]# kubectl get cs
NAME                 STATUS    MESSAGE             ERROR
controller-manager   Healthy   ok
scheduler            Healthy   ok
etcd-0               Healthy   {"health":"true"}


[root@k8s-m01 ~]# kubectl get  nodes
NAME      STATUS     ROLES    AGE     VERSION
k8s-m01   NotReady   master   6m31s   v1.18.0

安装网络插件flannel

简介:
Flannel是 CoreOS 团队针对 Kubernetes 设计的一个覆盖网络(Overlay Network)工具,其目的在于帮助每一个使用 Kuberentes 的 CoreOS 主机拥有一个完整的子网。这次的分享内容将从Flannel的介绍、工作原理及安装和配置三方面来介绍这个工具的使用方法。
Flannel通过给每台宿主机分配一个子网的方式为容器提供虚拟网络,它基于Linux TUN/TAP,使用UDP封装IP包来创建overlay网络,并借助etcd维护网络的分配情况。
Flannel是一种基于overlay网络的跨主机容器网络解决方案 ,也就是将TCP数据包封装在另一种网络包里面进行路由转发和通信, Flannel是CoreOS开发专门用于docker多机互联的一个工具,让集群中的不同节点主机创建的容器都具有全集群唯一的虚拟ip地址。
Flannel使用go语言编写。
Flannel实现原理
Flannel为每个host分配-个subnet ,容器从这个subnet中分配IP ,这些IP可以在host间路由,容器间无需使用nat和端口映射即可实现跨主机通信。
每个subnet都是从一个更大的IP池中划分的, flannel会在每个主机上运行一个叫flanneld的agent ,其职责就是从池子中分配subnet。
Flannel使用etcd存放网络配置、已分配的subnet. host的IP等信息。
Flannel数据包在主机间转发是由backend实现的,目前已经支持UDP、VxLAN、 host-gw. AWS VPC和GCE路由等多种backend.

下载 flannel YAML 文件

curl -o kube-flannel.yml https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

注意:
flannel默认会使用主机的第-一张物理网卡,如果你有多张网卡,需要通过配置单独指定。修改kube-flannel.yml中的以下部分。

修改yml文件

[root@ k8s-m01 ~] vim kube-flannel.yml

在这里插入图片描述

执行kube-flannel.yml

[root@k8s-m01 ~]# kubectl apply -f kube-flannel.yml
podsecuritypolicy.policy/psp.flannel.unprivileged created
clusterrole.rbac.authorization.k8s.io/flannel created
clusterrolebinding.rbac.authorization.k8s.io/flannel created
serviceaccount/flannel created
configmap/kube-flannel-cfg created
daemonset.apps/kube-flannel-ds created
[root@k8s-m01 ~]# kubectl get pods --all-namespaces -o wide
NAMESPACE     NAME                              READY   STATUS     RESTARTS   AGE   IP              NODE      NOMINATED NODE   READINESS GATES
kube-system   coredns-66bff467f8-h878c          0/1     Pending    0          16m   <none>           <none>    <none>           <none>
kube-system   coredns-66bff467f8-jb6xs          0/1     Pending    0          16m   <none>           <none>    <none>           <none>
kube-system   etcd-k8s-m01                      1/1     Running    79         16m   192.168.100.20   k8s-m01   <none>           <none>
kube-system   kube-apiserver-k8s-m01            1/1     Running    57         16m   192.168.100.20   k8s-m01   <none>           <none>
kube-system   kube-controller-manager-k8s-m01   1/1     Running    4          16m   192.168.100.20   k8s-m01   <none>           <none>
kube-system   kube-flannel-ds-qsh44             0/1     Init:0/1   0          14s   192.168.100.20   k8s-m01   <none>           <none>
kube-system   kube-proxy-55b6q                  1/1     Running    0          16m   192.168.100.20   k8s-m01   <none>           <none>
kube-system   kube-scheduler-k8s-m01            1/1     Running    4          16m   192.168.100.20   k8s-m01   <none>           <none>
[root@k8s-m01 ~]#  kubectl get nodes
NAME      STATUS   ROLES    AGE   VERSION
k8s-m01   Ready    master   17m   v1.18.0
[root@k8s-m01 ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   17m
[root@k8s-m01 ~]# kubectl get cs
NAME                 STATUS    MESSAGE             ERROR
scheduler            Healthy   ok
controller-manager   Healthy   ok
etcd-0               Healthy   {"health":"true"}
[root@k8s-m01 ~]#

加入node节点,

节点(node)是工作负载(容器和pod等运行的地方,如果要向集群添加新节点,请为每台机器执行以下操作:
● node节点执行1.1.2初始化准备
● 下载安装镜像.
● 执行kubeadm.join

在两台主机上,下载安装镜像

node上也是需要下载安装一些镜像的,需要下载的镜像为: kube-proxy, pause, flannel
[root@k8s-m02 ~]# cat >flannel.images<<EOF
 v0.12.0-amd64
v0.12.0-arm
 v0.12.0-arm64
v0.12.0-ppc64le
 v0.12.0-s390x
 EOF
[root@k8s-m02 ~]# for i in `cat flannel.images`
 do
     sudo docker pull registry.cn-beijing.aliyuncs.com/crazywjj/flannel:$i
     sudo docker tag  registry.cn-beijing.aliyuncs.com/crazywjj/flannel:$i quay.io/coreos/flannel:$i
     sudo docker rmi -f registry.cn-beijing.aliyuncs.com/crazywjj/flannel:$i
 done

将node 加入 master 节点

kubeadm join 192.168.100.20:6443 --token abcdef.0123456789abcdef \
    --discovery-token-ca-cert-hash sha256:5c452f5eaee37c6ae331878e524cda7b67dc466909100df91b73cd007e97d35c


[root@k8s-m01 ~]# kubectl get node
NAME      STATUS   ROLES    AGE   VERSION
k8s-m01   Ready    master   22m   v1.18.0
k8s-m02   Ready    <none>   40s   v1.18.0


[root@k8s-m01 ~]# kubectl get pods -n kube-system
NAME                              READY   STATUS    RESTARTS   AGE
coredns-66bff467f8-h878c          1/1     Running   0          22m
coredns-66bff467f8-jb6xs          1/1     Running   0          22m
etcd-k8s-m01                      1/1     Running   79         23m
kube-apiserver-k8s-m01            1/1     Running   57         23m
kube-controller-manager-k8s-m01   1/1     Running   4          23m
kube-flannel-ds-nxjpk             1/1     Running   0          76s
kube-flannel-ds-qsh44             1/1     Running   0          6m37s
kube-proxy-55b6q                  1/1     Running   0          22m
kube-proxy-d7fhh                  1/1     Running   0          76s
kube-scheduler-k8s-m01            1/1     Running   4          23m

验证kubernetes功能,

在master上创建测试文件

[root@k8s-m01 ~]#  cat > nginx-ds.yml <<EOF
 apiVersion: v1
 kind: Service
 metadata:
   name: nginx-ds
   labels:
     app: nginx-ds
 spec:
   type: NodePort
   selector:
     app: nginx-ds
   ports:
   - name: http
     port: 80
     targetPort: 80
 ---
 apiVersion: apps/v1
 kind: DaemonSet
 metadata:
   name: nginx-ds
   labels:
     addonmanager.kubernetes.io/mode: Reconcile
 spec:
   selector:
     matchLabels:
       app: nginx-ds
   template:
     metadata:
       labels:
         app: nginx-ds
     spec:
       containers:
       - name: my-nginx
         image: daocloud.io/library/nginx:latest
         ports:
         - containerPort: 80
 EOF
[root@k8s-m01 ~]#  kubectl create -f nginx-ds.yml
service/nginx-ds created
daemonset.apps/nginx-ds created
[root@k8s-m01 ~]# kubectl get pods -o wide|grep nginx-ds
nginx-ds-m5l6t   1/1     Running   0          11s   10.244.1.2   k8s-m02   <none>     <none>

[root@k8s-m01 ~]# ping -c 3 10.244.1.2
PING 10.244.1.2 (10.244.1.2) 56(84) bytes of data.
64 bytes from 10.244.1.2: icmp_seq=1 ttl=63 time=0.782 ms
64 bytes from 10.244.1.2: icmp_seq=2 ttl=63 time=1.28 ms
64 bytes from 10.244.1.2: icmp_seq=3 ttl=63 time=0.515 ms

--- 10.244.1.2 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 0.515/0.859/1.282/0.319 ms
[root@k8s-m01 ~]#  kubectl get svc
NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1      <none>        443/TCP        28m
nginx-ds     NodePort    10.98.52.201   <none>        80:32030/TCP   67s
[root@k8s-m01 ~]# curl 192.168.100.21:32030
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@k8s-m01 ~]#

在这里插入图片描述

移除node节点

在master节点执行

[root@k8s-m01 ~]# kubectl drain k8s-m02 --delete-local-data --force --ignore-daemonsetsnode/k8s-m02 cordoned
WARNING: ignoring DaemonSet-managed Pods: default/nginx-ds-m5l6t, kube-system/kube-flannel-ds-nxjpk, kube-system/kube-proxy-d7fhh
node/k8s-m02 drained
[root@k8s-m01 ~]# kubectl delete node k8s-m02
node "k8s-m02" deleted

Node 节点上的操作

[root@ k8s-m02 ~] kubeadm reset

[root@k8s-m02 ~]# systemctl stop docker
[root@k8s-m02 ~]# rm -rf /var/lib/cni/ /var/lib/kubelet/* /etc/cni/
[root@k8s-m02 ~]# ifconfig cni0 down
[root@k8s-m02 ~]# ifconfig flannel.1 down
[root@k8s-m02 ~]#  ifconfig docker0 down
[root@k8s-m02 ~]# ip link delete cni0
[root@k8s-m02 ~]# ip link delete flannel.1
[root@k8s-m02 ~]#
[root@k8s-m02 ~]# systemctl start docker
[root@k8s-m02 ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS             PORTS               NAMES
[root@k8s-m02 ~]#

三 . Dashboard界面

Dashboard 是基于网页的 Kubernetes 用户界面。可以使用 Dashboard 将容器应用部署到 Kubernetes 集群中,也可以对容器应用排错,还能管理集群本身及其附属资源。可以使用 Dashboard 获取运行在集群中的应用的概览信息,也可以创建或者修改 Kubernetes 资源(如 Deployment,Job,DaemonSet 等等)。例如,您可以对 Deployment 实现弹性伸缩、发起滚动升级、重启 Pod 或者使用向导创建新的应用。
在kubernetes Dashboard中可以查看集群中应用的运行状态,也能够创建和修改各种kubernetes资源(比如Deployment,Job,Daemonset等等),用户可以对Deployment实现弹性伸缩,执行滚动升级,重启pod或者使用向导创建新的应用。
可以说,kubernetes Dashboard提供了kubectl的绝大部分功能。
1,全面的群集管理:命名空间,节点,窗格,副本集,部署,存储,RBAC创建修改等
2,快速且始终如一的即时更新:无需刷新页面即可查看最新信息
3,快速查看集群运行状况:实时图表可帮助快速跟踪性能不佳的资源
4,易于CRUD和扩展:加上内联API文档,可以轻松了解每个字段的作用
5,简单的OpenID集成:无需特殊代理
Dashboard 同时展示了kubernetes集群中的资源状态信息和所有报错信息。

下载 dashboard 文件

[root@k8s-m01 ~]# curl -o dashboard-recommended.yaml https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-rc7/aio/deploy/recommended.yaml
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  7566  100  7566    0     0   3362      0  0:00:02  0:00:02 --:--:--  3361
[root@k8s-m01 ~]# kubectl apply -f  dashboard-recommended.yaml


[root@k8s-m01 ~]# kubectl get all -n kubernetes-dashboard
NAME                                            READY   STATUS    RESTARTS   AGE
pod/dashboard-metrics-scraper-dc6947fbf-gtmcx   1/1     Running   0          31s
pod/kubernetes-dashboard-5d4dc8b976-xg8ms       1/1     Running   0          31s

NAME                                TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)  AGE
service/dashboard-metrics-scraper   ClusterIP   10.108.12.152   <none>        8000/TCP  31s
service/kubernetes-dashboard        ClusterIP   10.108.66.210   <none>        443/TCP  31s

NAME                                        READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/dashboard-metrics-scraper   1/1     1            1           31s
deployment.apps/kubernetes-dashboard        1/1     1            1           31s

NAME                                                  DESIRED   CURRENT   READY   AGE
replicaset.apps/dashboard-metrics-scraper-dc6947fbf   1         1         1       31s
replicaset.apps/kubernetes-dashboard-5d4dc8b976       1         1         1       31s
[root@k8s-m01 ~]#

访问 dashboard

2,访问 dashboard

dashboard 只允许通过 https 访问,如果使用 kube proxy 则必须监听 localhost 或 127.0.0.1。对于 NodePort 没有这个限制,但是仅建议在开发环境中使用。对于不满足这些条件的登录访问,在登录成功后浏览器不跳转,始终停在登录界面。

访问方式:
Dashboard的github https://github.com/kubernetes/dashboard/blob/master/docs/user/accessing-dashboard/1.7.x-and-above.md

kubectl proxy:
kubectl proxy在您的机器和Kubernetes API服务器之间创建代理服务器。默认情况下,只能在本地(从启动它的计算机上)访问它。

kubectl port-forward:
通过端口转发映射本地端口到指定的应用端口,从而访问集群中的应用程序(Pod)。

NodePort:
这种方法只推荐使用在一个node节点的方案,在大多数的环境都需要多个node节点,因此这种方法没有什么实用价值,不建议使用。

API Server:
如果Kubernetes API服务器是公开的并且可以从外部访问,则可以直接在以下位置访问仪表板: https://:/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/

注意:
仅当您选择在浏览器中安装用户证书时,才可以使用这种方式访问Dashboard。在示例中,可以使用kubeconfig文件用于联系API服务器的证书。

Ingress

采用API Server访问: https://192.168.100.20:6443/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/

在这里插入图片描述
我们使用的是system:anonymous用户来访问位于kube-system命名空间中的名为https:kubernetes-dashboard的service资源。这个用户没有权限访问,所以被拒绝了。

3,生成浏览器访问证书

dashboard 默认只支持 token 认证(不支持 client 证书认证),所以如果使用 Kubeconfig 文件,需要将 token 写入到该文件。
创建证书:
首先需要确认kubectl命令的配置文件,默认情况下为/etc/kubernetes/admin.conf,而且已经自动创建在$HOME/.kube/config中,如果没有创建则需要手动赋值。

3.1,创建kubectl配置文件

root@ k8s-m01 ~] cat $HOME/.kube/config
[root@k8s-m01 ~]# cd /etc/kubernetes/pki
[root@k8s-m01 pki]# grep 'client-certificate-data' ~/.kube/config | head -n 1 | awk '{print $2}' | base64 -d > dashboard.crt
[root@k8s-m01 pki]# grep 'client-key-data' ~/.kube/config | head -n 1 | awk '{print $2}' | base64 -d > dashboard.key
[root@k8s-m01 pki]# openssl pkcs12 -export -clcerts -inkey dashboard.key -in dashboard.crt -out dashboard.p12 -name "kubernetes-client"
Enter Export Password:
Verifying - Enter Export Password:
[root@k8s-m01 pki]# ls
apiserver.crt                 ca.crt         front-proxy-ca.crt
apiserver-etcd-client.crt     ca.key         front-proxy-ca.key
apiserver-etcd-client.key     dashboard.crt  front-proxy-client.crt
apiserver.key                 dashboard.key  front-proxy-client.key
apiserver-kubelet-client.crt  dashboard.p12  sa.key
apiserver-kubelet-client.key  etcd           sa.pub
[root@k8s-m01 pki]# pwd
/etc/kubernetes/pki

4,将生成的dashboard.p12证书下载到Windows桌面上,然后导入浏览器

谷歌(Google)或者火狐(Firefox)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

5,登录dashboard

5.1,创建登录dashboard的token和kubeconfig配置文件

方法1:
可以使用输出的token,登录dashboard

[root@k8s-m01 pki]# echo ${DASHBOARD_LOGIN_TOKEN}
eyJhbGciOiJSUzI1NiIsImtpZCI6Ik8xc1BwQXRFWkc4R3pQUHhfX0pHNjNJQzRQMUlqNlQ0ZTVFMDlueUNLcXcifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tZnBudnYiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNTNjYzU2ZWUtNmUxNy00ZTQzLWExMmMtNTY5MmI4ZDYzNjkwIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.cOSB29zUPKtc9DUFGJ6PZOfHf_UzLse7Sm_JyjYkdf5LMf_T2omkq93-s6nBcjRI27FgIbW_B6Hg0inZ35quIyxmvpMtPBN9NMhFjeUPW_ZOLaRc6WUeXpIKcJ0piclFipay3BnHazL0K41MPWZCfNjA6OBMfP5i_GZGYn36QYj9Km9LaniYE55Lirw6NlA1meenoJ1BDXVHmOF9d2rqHB9pBFuh_KxjgYrPSyxIDNMqDguraeqKZ1Xdl_Drk9YXTjRg2hg79DvpzjYqSY4KTdFGuA5xfN-vwbcc_TkH08jyCkJdD08hxMquZ3GXWqTFxewnx6Idk_auFqDqo7dBew
[root@k8s-m01 pki]#

重启浏览器,重新访问
https://192.168.100.20:6443/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/

输入获取到的 token
在这里插入图片描述
方法2:
将Dashboard.Kubeconfig文件下载到电脑端,用生成的Dashboard.Kubeconfig登录dashboard

KUBE_APISERVER="https://192.168.100.20:6443" 
DASHBOARD_LOGIN_TOKEN=$(kubectl describe secret -n kube-system ${ADMIN_SECRET} | grep -E '^token' | awk '{print $2}') 
# 设置集群参数 
kubectl config set-cluster kubernetes \ --certificate-authority=/etc/kubernetes/pki/ca.crt \ --embed-certs=true \ --server=${KUBE_APISERVER} \ --kubeconfig=dashboard.kubeconfig 
# 设置客户端认证参数,使用上面创建的
 Token kubectl config set-credentials dashboard_user \ --token=${DASHBOARD_LOGIN_TOKEN} \ --kubeconfig=dashboard.kubeconfig 
# 设置上下文参数 kubectl config set-context default \ --cluster=kubernetes \ --user=dashboard_user \ --kubeconfig=dashboard.kubeconfig
 # 设置默认上下文 
kubectl config use-context default --kubeconfig=dashboard.kubeconfig




[root@k8s-m01 pki]# KUBE_APISERVER="https://192.168.100.20:6443"
[root@k8s-m01 pki]# DASHBOARD_LOGIN_TOKEN=$(kubectl describe secret -n kube-system ${ADMIN_SECRET} | grep -E '^token' | awk '{print $2}')
[root@k8s-m01 pki]# kubectl config set-cluster kubernetes \
>   --certificate-authority=/etc/kubernetes/pki/ca.crt \
>   --embed-certs=true \
>   --server=${KUBE_APISERVER} \
>   --kubeconfig=dashboard.kubeconfig
Cluster "kubernetes" set.
[root@k8s-m01 pki]# kubectl config set-credentials dashboard_user \
>   --token=${DASHBOARD_LOGIN_TOKEN} \
>   --kubeconfig=dashboard.kubeconfig
User "dashboard_user" set.
[root@k8s-m01 pki]# kubectl config set-context default \
>   --cluster=kubernetes \
>   --user=dashboard_user \
>   --kubeconfig=dashboard.kubeconfig
Context "default" created.
[root@k8s-m01 pki]# kubectl config use-context default --kubeconfig=dashboard.kubeconfig
Switched to context "default".
[root@k8s-m01 pki]# ls
apiserver.crt                 ca.key                front-proxy-ca.key
apiserver-etcd-client.crt     dashboard.crt         front-proxy-client.crt
apiserver-etcd-client.key     dashboard.key         front-proxy-client.key
apiserver.key                 dashboard.kubeconfig  sa.key
apiserver-kubelet-client.crt  dashboard.p12         sa.pub
apiserver-kubelet-client.key  etcd
ca.crt                        front-proxy-ca.crt

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值