K8s Kubernetes集群部署

Posted AK774S

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了K8s Kubernetes集群部署相关的知识,希望对你有一定的参考价值。

[root@master ~]# yum -y install docker-ce

[root@master ~]# systemctl enable --now docker

Created symlink /etc/systemd/system/multi-user.target.wants/docker.service → /usr/lib/systemd/system/docker.service.

[root@master ~]# docker --version

Docker version 20.10.12, build e91ed57

[root@master ~]# ls /etc/docker/

key.json

//镜像加速

[root@master ~]# cat > /etc/docker/daemon.json << EOF

“registry-mirrors”: [“https://b9pmyelo.mirror.aliyuncs.com”],

“exec-opts”: [“native.cgroupdriver=systemd”],

“log-driver”: “json-file”,

“log-opts”:

“max-size”: “100m”

,

“storage-driver”: “overlay2”

EOF

[](()添加kubernetes阿里云YUM软件源

[root@master ~]# 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

[root@master ~]# yum clean all && yum makecache

[](()安装kubeadm,kubelet和kubectl

//安装kubeadm,kubelet和kubectl,由于版本更新频繁,这里指定版本号部署

[root@master ~]# yum install -y kubelet-1.20.0 kubeadm-1.20.0 kubectl-1.20.0

[root@master ~]# systemctl enable kubelet

Created symlink /etc/systemd/system/multi-user.target.wants/kubelet.service → /usr/lib/systemd/system/kubelet.service.

[root@master ~]# systemctl status kubelet

● kubelet.service - kubelet: The Kubernetes Node Agent

Loaded: loaded (/usr/lib/systemd/system/kubelet.service; enabled; vendor preset: disabled)

Drop-In: /usr/lib/systemd/system/kubelet.service.d

└─10-kubeadm.conf

Active: inactive (dead)

Docs: https://kubernetes.io/docs/

[](()部署Kubernetes Master


[root@master ~]# kubeadm init --apiserver-advertise-address 192.168.129.250 --image-repository registry.aliyuncs.com/google_containers --kubernetes-version v1.20.0 --service-cidr 10.96.0.0/12 --pod-network-cidr 10.244.0.0/16

[init] Using Kubernetes version: v1.20.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/

[WARNING FileExisting-tc]: tc not found in system path

[WARNING SystemVerification]: this Docker version is not on the list of validated versions: 20.10.12. Latest validated version: 19.03

[preflight] Pulling images required for setting up a Kubernetes cluster

[preflight] This might take a minute or two, depending on the speed of your internet connection

[preflight] You can also perform this action in beforehand using ‘kubeadm config images pull’

[certs] Using certificateDir folder “/etc/kubernetes/pki”

[certs] Generating “ca” certificate and key

[certs] Generating “apiserver” certificate and key

[certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local master] and IPs [10.96.0.1 192.168.129.250]

[certs] Generating “apiserver-kubelet-client” certificate and key

[certs] Generating “front-proxy-ca” certificate and key

[certs] Generating “front-proxy-client” certificate and key

[certs] Generating “etcd/ca” certificate and key

[certs] Generating “etcd/server” certificate and key

[certs] etcd/server serving cert is signed for DNS names [localhost master] and IPs [192.168.129.250 127.0.0.1 ::1]

[certs] Generating “etcd/peer” certificate and key

[certs] etcd/peer serving cert is signed for DNS names [localhost master] and IPs [192.168.129.250 127.0.0.1 ::1]

[certs] Generating “etcd/healthcheck-client” certificate and key

[certs] Generating “apiserver-etcd-client” certificate and key

[certs] Generating “sa” key and public key

[kubeconfig] Using kubeconfig folder “/etc/kubernetes”

[kubeconfig] Writing “admin.conf” kubeconfig file

[kubeconfig] Writing “kubelet.conf” kubeconfig file

[kubeconfig] Writing “controller-manager.conf” kubeconfig file

[kubeconfig] Writing “scheduler.conf” kubeconfig file

[kubelet-start] Writing kubelet environment file with flags to file “/var/lib/kubelet/kubeadm-flags.env”

[kubelet-start] Writing kubelet configuration to file “/var/lib/kubelet/config.yaml”

[kubelet-start] Starting the kubelet

[control-plane] Using manifest folder “/etc/kubernetes/manifests”

[control-plane] Creating static Pod manifest for “kube-apiserver”

[control-plane] Creating static Pod manifest for “kube-controller-manager”

[control-plane] Creating static Pod manifest for “kube-scheduler”

[etcd] Creating static Pod manifest for local etcd in “/etc/kubernetes/manifests”

[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory “/etc/kubernetes/manifests”. This can take up to 4m0s

[apiclient] All control plane components are healthy after 8.506240 seconds

[upload-config] Storing the configuration used in ConfigMap “kubeadm-config” in the “kube-system” Namespace

[kubelet] Creating a ConfigMap “kubelet-config-1.20” 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 master as control-plane by adding the labels “node-role.kubernetes.io/master=‘’” and “node-role.kubernetes.io/control-plane=‘’ (deprecated)”

[mark-control-plane] Marking the node master as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]

[bootstrap-token] Using token: akxmi3.rtm7hjgs7n9trljm

[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 ( i d − u ) : (id -u): (idu):(id -g) $HOME/.kube/config

Alternatively, if you are the root user, you can run:

export KUBECONFIG=/etc/kubernetes/admin.conf

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.129.250:6443 --token hglo7o.0ya3tbi82wqdjif4 \\

–discovery-token-ca-cert-hash sha256:f6be891c6cd273a9283a6c05ca795811f7350afa2b5072990a294b7070ff9a4f

//把那条命令写入到文件中保存起来(以防万一)

[root@master ~]# vim init

kubeadm join 192.168.129.250:6443 --token hglo7o.0ya3tbi82wqdjif4 \\

–discovery-token-ca-cert-hash sha256:f6be891c6cd273a9283a6c05ca795811f7350afa2b5072990a294b7070ff9a4f

[root@master ~]# docker images

REPOSITORY TAG IMAGE ID CREATED SIZE

registry.aliyuncs.com/google_containers/kube-proxy v1.20.0 10cc881966cf 12 months ago 118MB

registry.aliyuncs.com/google_containers/kube-scheduler v1.20.0 3138b6e3d471 12 months ago 46.4MB

registry.aliyuncs.com/google_containers/kube-apiserver v1.20.0 ca9843d3b545 12 months ago 122MB

registry.aliyuncs.com/google_containers/kube-controller-manager v1.20.0 b9fa1895dcaa 12 months ago 116MB

registry.aliyuncs.com/google_containers/etcd 3.4.13-0 0369cf4303ff 15 months ago 253MB

registry.aliyuncs.com/google_containers/coredns 1.7.0 bfe3a36ebd25 18 months ago 45.2MB

registry.aliyuncs.com/google_containers/pause 3.2 80d28bedfe5d 22 months ago 683kB

//设置环境变量

[root@master ~]# echo ‘export KUBECONFIG=/etc/kubernetes/admin.conf’ > /etc/profile.d/k8s.sh

[root@master ~]# source /etc/profile.d/k8s.sh

[root@master ~]# echo $KUBECONFIG

/etc/kubernetes/admin.conf

[root@master ~]# kubectl get nodes

NAME STATUS ROLES AGE VERSION

master Ready control-plane,master 76m v1.20.0 #要Ready(时间会有点长)

[](()安装Pod网络插件(CNI)


[root@master ~]# kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

The connection to the server raw.githubusercontent.com was refused - did you specify the right host or port? #出现此报错

//解决方案

[root@master ~]# cat /etc/hosts //添加如下内容

199.232.96.133 raw.githubusercontent.com

[root@master ~]# kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/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

确保能访问到这个网站

[quay.io](()

[](()加入Kubernetes Node


在node1与node2节点上执行

向集群添加新节点,执行在kubeadm init输出的kubeadm join命令:

//这里执行的就是我们刚才保存的init文件里面的内容

[root@node1 ~]# kubeadm join 192.168.129.250:6443 --token hglo7o.0ya3tbi82wqdjif4 --discovery-token-ca-cert-hash sha256:f6be891c6cd273a9283a6c05ca795811f7350afa2b5072990a294b7070ff9a4f

[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/

[WARNING FileExisting-tc]: tc not found in system path

[WARNING SystemVerification]: this Docker version is not on the list of validated versions: 20.10.12. Latest validated version: 19.03

[WARNING Hostname]: hostname “node1” could not be reached

[WARNING Hostname]: hostname “node1”: lookup node1 on 192.168.129.2:53: no such host

[preflight] Reading configuration from the cluster…

[preflight] FYI: You can look at this config file with ‘kubectl -n kube-system get cm kubeadm-config -o yaml’

[kubelet-start] Writing kubelet configuration to file “/var/lib/kubelet/config.yaml”

[kubelet-start] Writing kubelet environment file with flags to file “/var/lib/kubelet/kubeadm-flags.env”

[kubelet-start] Starting the kubelet

[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap…

This node has joined the cluster:

  • Certificate signing request was sent to apiserver and a response was received.

  • The Kubelet was informed of the new secure connection details.

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

// 在node2上执行

[root@node2 ~]# kubeadm join 192.168.129.250:6443 --token hglo7o.0ya3tbi82wqdjif4 --discovery-token-ca-cert-hash sha256:f6be891c6cd273a9283a6c05ca795811f7350afa2b5072990a294b7070ff9a4f

[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/

[WARNING FileExisting-tc]: tc not found in system path

[WARNING SystemVerification]: this Docker version is not on the list of validated versions: 20.10.12. Latest validated version: 19.03

[WARNING Hostname]: hostname “node2” could not be reached

[WARNING Hostname]: hostname “node2”: lookup node2 on 114.114.114.114:53: no such host

[preflight] Reading configuration from the cluster…

[preflight] FYI: You can look at this config file with ‘kubectl -n kube-system get cm kubeadm-config -o yaml’

[kubelet-start] Writing kubelet configuration to file “/var/lib/kubelet/config.yaml”

[kubelet-start] Writing kubelet environment file with flags to file “/var/lib/kubelet/kubeadm-flags.env”

[kubelet-start] Starting the kubelet

[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap…

This node has joined the cluster:

  • Certificate signing request was sent to apiserver and a response was received.

  • The Kubelet was informed of the new secure connection details.

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

[](()测试kubernetes集群


// 查看节点的状态

[root@master ~]# kubectl get nodes

NAME STATUS ROLES AGE VERSION

master Ready control-plane,master 80m v1.20.0

node1 NotReady 69s v1.20.0 #等待状态变为Ready

node2 NotReady 52s v1.20.0 #等待状态变为Ready

[root@master ~]# kubectl get nodes

NAME STATUS ROLES AGE VERSION

master Ready control-plane,master 86m v1.20.0

node1 Ready 6m17s v1.20.0

node2 Ready 6m v1.20.0

[root@master ~]# kubectl get ns

NAME STATUS AGE

default Active 89m

kube-node-lease Active 89m

kube-public Active 89m

kube-system Active 89m

[root@master ~]# kubectl get pods -n kube-system -o wide

NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES

coredns-7f89b7bc75-qjjmz 1/1 Running 0 91m 10.244.0.3 master

coredns-7f89b7bc75-rvcdl 1/1 Running 0 91m 10.244.0.2 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 master

etcd-master 1/1 Running 0 91m 192.168.129.250 master

kube-apiserver-master 1/1 Running 0 91m 192.168.129.250 master

kube-controller-manager-master 1/1 Running 0 91m 192.168.129.250 master

kube-flannel-ds-7stlz 1/1 Running 0 12m 192.168.129.135 node1

kube-flannel-ds-7xthp 1/1 Running 0 58m 192.168.129.250 master

kube-flannel-ds-mzw2x 1/1 Running 0 11m 192.168.129.136 node2

kube-proxy-b8qnc 1/1 Running 0 91m 192.168.129.250 master

kube-proxy-gr294 1/1 Running 0 12m 192.168.129.135 node1

kube-proxy-mtgnd 1/1 Running 0 11m 192.168.129.136 node2

kube-scheduler-master 1/1 Running 0 91m 192.168.129.250 master

[root@master ~]# kubectl create deployment nginx --image=nginx //运行一个nginx的pod

deployment.apps/nginx created

[root@master ~]# kubectl expose deployment nginx --port=80 --type=NodePort //映射80端口

service/nginx exposed

[root@master ~]# kubectl get pods,svc

NAME READY STATUS RESTARTS AGE

pod/nginx-6799fc88d8-8hwr2 0/1 ContainerCreating 0 33s

NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE

service/kubernetes ClusterIP 10.96.0.1 443/TCP 87m

service/nginx NodePort 10.111.93.135 80:30274/TCP 24s

[root@master ~]# curl http://10.111.93.135

Kubernetes——Kubernetes基础+部署Kubernetes集群

Kubernetes基础+部署Kubernetes集群

Kubernetes介绍

1.1 应用部署方式演变

在部署应用程序的方式上,主要经历了三个时代:

  • 传统部署:互联网早期,会直接将应用程序部署在物理机上

优点:简单,不需要其它技术的参与
缺点:不能为应用程序定义资源使用边界,很难合理地分配计算资源,而且程序之间容易产生影响

  • 虚拟化部署:可以在一台物理机上运行多个虚拟机,每个虚拟机都是独立的一个环境

优点:程序环境不会相互产生影响,提供了一定程度的安全性
缺点:增加了操作系统,浪费了部分资源

  • 容器化部署:与虚拟化类似,但是共享了操作系统

优点:
可以保证每个容器拥有自己的文件系统、CPU、内存、进程空间等
运行应用程序所需要的资源都被容器包装,并和底层基础架构解耦
容器化的应用程序可以跨云服务商、跨Linux操作系统发行版进行部署

  • 容器化部署方式给带来很多的便利,但是也会出现一些问题,比如说:
    • 一个容器故障停机了,怎么样让另外一个容器立刻启动去替补停机的容器
    • 当并发访问量变大的时候,怎么样做到横向扩展容器数量
  • 这些容器管理的问题统称为容器编排问题,为了解决这些容器编排问题,就产生了一些容器编排的软件:
    • Swarm: Docker自己的容器编排工具
    • Mesos: Apache的一个资源统—管控的工具,需要和Marathon结合使用
    • Kubernetes : Google开源的的容器编排工具

1.2 Kubernetes简介

  • kubernetes,是一个全新的基于容器技术的分布式架构领先方案,是谷歌严格保密十几年的秘密武器–Borg系统的一个开源版本,于2014年9月发布第一个版本,2015年7月发布第一个正式版本。
  • kubernetes的本质是一组服务器集群,它可以在集群的每个节点上运行特定的程序,来对节点中的容器进行管理。它的目的就是是实现资源管理的自动化,主要提供了如下的主要功能:
    • 自我修复:一旦某一个容器崩溃,能够在1秒中左右迅速启动新的容器
    • 弹性伸缩:可以根据需要,自动对集群中正在运行的容器数进行调整
    • 服务发现:服务可以通过自动发现的形式找到它所依赖的服务
    • 负载均衡:如果一个服务起动了多个容器,能够自动实现请求的负载均衡
    • 版本回退:如果发现新发布的程序版本有问题。可以立即回退到原来的版本
    • 存储编排:可以根据容器自身的需求自动创建存储卷

1.3 Kubernetes组件

一个kubernetes集群主要是由控制节点(master)、工作节点(node)构成,每个节点上都会安装不同的组件。

  • Master:集群的控制平面,负责集群的决策

ApiServer:资源操作的唯一入口,接收用户输入的命令,提供认证、授权、API注册和发现等机制
Scheduler:负责集群资源调度,按照预定的调度策略将Pod调度到相应的node节点上
ControllerManager:负责维护集群的状态,比如程序部署安排、故障检测、自动扩展、滚动更新等
Etcd:负责存储集群中各种资源对象的信息

  • Node:集群的数据平面,负责为容器提供运行环境

Kubelet:负责维护容器的生命周期,即通过控制docker,来创建、更新、销毁容器
KubeProxy:负责提供集群内部的服务发现和负载均衡
Docker:负责节点上容器的各种操作

  • 部署一个nginx服务来说明kubernetes系统各个组件调用关系:
    • 首先要明确,一旦kubernetes环境启动之后,master和node都会将自身的信息存储到etcd数据库中
    • 一个nginx服务的安装请求会首先被发送到master节点的apiServer组件
    • apiServer组件会调用scheduler组件来决定到底应该把这个服务安装到哪个node节点上,在此时,它会从etcd中读取各个node节点的信息,然后按照一定的算法进行选择,并将结果告知apiServer
    • apiServer调用controller-manager去调度Node节点安装nginx服务
    • kubelet接收到指令后,会通知docker,然后由docker来启动一个nginx的podpod是kubernetes的最小操作单元,容器必须跑在pod中至此
    • 一个nginx服务就运行了,如果需要访问nginx,就需要通过kube-proxy来对pod产生访问的代理,这样,外界用户就可以访问集群中的nginx服务了

1.4 Kubernetes概念

  • Master:集群控制节点,每个集群需要至少一个master节点负责集群的管控
  • Node:工作负载节点,由master分配容器到这些node工作节点上,然后node节点上的docker负责容器的运行
  • Pod:kubernetes的最小控制单元,容器都是运行在pod中的,一个pod中可以有1个或者多个容器(部署程序 > 容器 > pod)
  • Controller:控制器,通过它来实现对pod的管理,比如启动pod、停止pod、伸缩pod的数量等等
  • Service:pod对外服务的统一入口,下面可以维护者同一类的多个pod
  • Label:标签,用于对pod进行分类,同一类pod会拥有相同的标签
  • NameSpace:命名空间,用来隔离pod的运行环境

集群环境搭建

2.1 环境规划

2.1.1 集群类型

  • kubernetes集群大体上分为两类:一主多从多主多从
    • 一主多从:一台Master节点和多台Node节点,搭建简单,但是有单机故障风险,适合用于测试环境
    • 多主多从:多台Master节点和多台Node节点,搭建麻烦,安全性高,适合用于生产环境

说明:为了测试简单,本次搭建的是一主两从类型的集群

2.1.2 安装方式

  • Kubernetes有多种部署方式,目前主流的方式有kubeadm、minikube、二进制包
    • Minikube:一个用于快速搭建单节点kubernetes的工具
    • Kubeadm:一个用于快速搭建kubernetes集群的工具
    • 二进制包∶从官网下载每个组件的二进制包,依次去安装,此方式对于理解kubernetes组件更加有效

说明:现在需要安装kubernetes的集群环境,但是又不想过于麻烦,所以选择使用kubeadm方式

2.1.3 主机规划

作用IP地址操作系统配置
k8s-master192.168.93.66CentOS 7.5 基础设施服务器2颗CPU 2G内存
k8s-node1192.168.93.88CentOS 7.5 基础设施服务器2颗CPU 2G内存
k8s-node2192.168.93.89CentOS 7.5 基础设施服务器2颗CPU 2G内存

2.2 环境初始化

  • 检查操作系统版本
#此方式下安装kubernetes集群要求centos版本要在7.5或之上
cat /etc/redhat-release 
CentOS Linux release 7.5.1804 (Core)
  • 主机名解析
# 为了方便后面集群节点间的直接调用,在这配置一下主机名解析,企业中推荐使用内部DNS服务器
# 主机名成解析编辑三台服务器的/etc/hosts文件,添加下面内容
# 使用Xsell发送键到所有会话

vim /etc/hosts
192.168.93.66 k8s-master
192.168.93.88 k8s-node1
192.168.93.89 k8s-node2
  • 时间同步
# kubernetes要求集群中的节点时间必须精确一致,这里直接使用chronyd服务从网络同步时间
# 企业中建议配置内部的时间同步服务器

# 查看是否安装
rpm -qa |grep chrony
# 安装,使用Xshell发送键到所有会话
yum install -y chrony
# 启动chrony服务并设置开机自启
systemctl start chronyd && systemctl enable chronyd

# 设置完成后查看时间是否同步
date
  • 禁用iptables和firewalld服务
# kubernetes和docker在运行中会产生大量的iptables规则,为了不让系统规则跟它们混淆,直接关闭系统的规则

# 关闭防火墙并设置开机不启动
systemctl stop firewalld && systemctl disable firewalld
# 当前版本没有iptables,这一步就算完成
  • 禁用Selinux
# selinux是linux系统下的一个安全服务,如果不关闭它,在安装集群中会产生各种各样的奇葩问题
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
setenforce 0
getenforce
  • 禁用swap交换分区
# swap分区指的是虚拟内存分区,它的作用是在物理内存使用完之后,将磁盘空间虚拟成内存来使用
# 启用swap设备会对系统的性能产生非常负面的影响,因此kubernetes要求每个节点都要禁用swap设备
# 但是如果因为某些原因确实不能关闭swap分区,就需要在集群安装过程中通过明确的参数进行配置说明

# 编辑分区配置文件/etc/fstab,注释掉swap分区一行
# 修改完毕之后需要重启linux服务
vim /etc/fstab
#/dev/mapper/centos-swap swap                    swap    defaults        0 0
  • 修改Linux内核参数
# 修改linux的内核参数,添加网桥过滤和地址转发功能
# 编辑/etc/sysctl.d/kubernetes.conf文件,添加如下配置:
vim /etc/sysctl.d/kubernetes.conf

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

# 重新加载配置
sysctl -p

# 加载网桥过滤模块
modprobe br_netfilter

# 查看网桥过滤模块是否加载成功
lsmod | grep br_netfilter
br_netfilter           22256  0
  • 配置ipvs功能
# 在kubernetes中service有两种代理模型,一种是基于iptables的,一种是基于ipvs的
# 两者比较的话,ipvs的性能明显要高一些,但是如果要使用它,需要手动载入ipvs模块

# 安装ipset和ipvsadm
yum install ipset ipvsadm -y

#添加需要加载的模块写入脚本文件
cat <<EOF > /etc/sysconfig/modules/ipvs.modules
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack_ipv4
EOF

# 为脚本添加执行权限
chmod +x /etc/sysconfig/modules/ipvs.modules

# 执行脚本文件
/bin/bash /etc/sysconfig/modules/ipvs.modules

# 查看对应模块是否加载成功
lsmod | grep -e ip_vs -e nf_conntrack_ipv4
  • 重启服务器
# 重启
reboot
# 重启后查看交换分区是否关闭成功
free -h

2.2.1 安装Docker

# 切换镜像源
wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo

# 查看当前镜像源中支持的docker版本
yum list docker-ce --showduplicates

# 安装特定版本的docker-ce
# 必须指定--setopt=obsoletes=0,否则yum会自动安装更高版本,稳定
yum install --setopt=obsoletes=0 docker-ce-18.06.3.ce-3.el7 -y

# 添加一个配置文件
# Docker在默认情况下使用的Cgroup Driver为cgroupfs,而kubernetes推荐使用systemd来代替cgroupfs
mkdir /etc/docker
cat <<EOF > /etc/docker/daemon.json
 
"exec-opts": ["native.cgroupdriver=systemd"],
"registry-mirrors":["https://kn0t2bca.mirror.aliyuncs.com"]
 
EOF
 
# 启动并设置开机启动docker
systemctl enable docker --now

#检查docker版本和状态
docker version

2.2.2 安装kubernetes组件

# 由于kubernetes的镜像源在国外,速度比较慢,这里切换成国内的镜像源

# 编辑/etc/yum.repos.d/kubernetes.repo,添加下面的配置
vim /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg
       http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg

# 安装kubeadm、kubelet和kubectl
yum install --setopt=obsoletes=0 kubeadm-1.17.4-0 kubelet-1.17.4-0 kubectl-1.17.4-0 -y

# 配置kubelet的cgroup
# 编辑/etc/sysconfig/kubelet,添加下面的配器
vim /etc/sysconfig/kubelet
KUBELET_CGROUP_ARGS="--cgroup-driver=systemd"
KUBE_PROXY_MODE="ipvs"

# 设置kubelet开机自启,不用手动启动,在集群启动中会自动启动
systemctl enable kubelet

2.2.3 准备集群镜像

#在安装kubernetes集群之前,必须要提前准备好集群需要的镜像,所需镜像可以通过下面命令查看
kubeadm config images list

# 下载镜像
# 定义下载镜像的列表,三台机器同时操作
images=(
kube-apiserver:v1.17.4
kube-controller-manager:v1.17.4
kube-scheduler:v1.17.4
kube-proxy:v1.17.4
pause:3.1
etcd:3.4.3-0
coredns:1.6.5
)

# 从阿里云仓库拉取镜像
# 拉取完成之后该为k8s官方仓库的名字
# 修改完成之后再移除以阿里开头的镜像

for imageName in $images[@] ;do
	docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName
	docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName k8s.gcr.io/$imageName
	docker rmi registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName
done

#下载完成后查看下载的镜像
docker images

2.2.4 集群初始化

对集群进行初始化,并将node节点加入到集群中
下面的操作只需要在master节点上执行即可

#创建集群
kubeadm init \\
--kubernetes-version=v1.17.4 \\               # k8s版本1.17.4
--pod-network-cidr=10.244.0.0/16 \\           # pod网络
--service-cidr=10.96.0.0/12 \\                # service网络
--apiserver-advertise-address=192.168.93.66  # 定义master节点IP地址

# 你的Kubernetes控制平面已成功初始化!
Your Kubernetes control-plane has initialized successfully! 

# 根据提示创建必要文件
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

下面的操作只需要在node节点上执行即可

# 将node节点加入集群

# 通过在每个节点上以root身份运行以下命令,可以加入任意数量的工作节点
Then you can join any number of worker nodes by running the following on each as root:

kubeadm join 192.168.93.66:6443 --token pondho.kj8ufmze063pd2k5 \\
    --discovery-token-ca-cert-hash sha256:9cdad3766150017fe9a0f432b3f5daa520454c6b6b1e1a05a8cc0bb03e41732e

# 在控制平面上运行"kubectl get nodes"以查看此节点是否加入集群
Run 'kubectl get nodes' on the control-plane to see this node join the cluster.

#在master节点查看,此时状态为NotReady,需要安装网络插件
[root@k8s-master ~]# kubectl get nodes
NAME         STATUS     ROLES    AGE     VERSION
k8s-master   NotReady   master   4m10s   v1.17.4
k8s-node1    NotReady   <none>   28s     v1.17.4
k8s-node2    NotReady   <none>   9s      v1.17.4

2.2.5 安装网络插件

  • kubernetes支持多种网络插件,比如flannel、calico、canal等等,任选一种使用即可,本次选择flannel

下面操作依旧只在master节点执行即可,插件使用的是DaemonSet的控制器,它会在每个节点上都运行

# 获取fannel的配置文件
wget https://github.com/mrlxxx/kube-flannel.yml/archive/refs/heads/master.zip
unzip master.zip
find kube-flannel.yml-master/ -name kube-flannel.yml -exec mv  . \\;
rm -rf kube-flannel.yml-master master.zip
vim kube-flannel.yml
# 修改文件中的quay.io仓库为quay-mirror.qiniu.com

# 每个节点都需要拉取镜像
docker pull lwolf/flannel:v0.12.0
# 为什么要打tag,因为kube-flannel.yaml文件里面的镜像名称就是quay.io/coreos/flannel:v0.12.0-amd64
docker tag lwolf/flannel:v0.12.0 quay-mirror.qiniu.com/coreos/flannel:v0.12.0-amd64

# 使用配置文件启动fannel网络
kubectl apply -f kube-flannel.yml

# 再次查看集群节点的状态
[root@k8s-master ~]# kubectl get nodes
NAME         STATUS   ROLES    AGE   VERSION
k8s-master   Ready    master   18m   v1.17.4
k8s-node1    Ready    <none>   14m   v1.17.4
k8s-node2    Ready    <none>   14m   v1.17.4
# 至此,kubernetes的集群环境搭建完成

2.3 服务部署

  • 接下来在kubernetes集群中部署一个nginx程序,测试下集群是否在正常工作。

下面操作依旧只在master节点执行即可

# 部署nginx
[root@k8s-master ~]# kubectl create deployment nginx --image=nginx:1.14-alpine
deployment.apps/nginx created

# 暴露端口,NodePort:让集群之外的人访问
[root@k8s-master ~]# kubectl expose deployment nginx --port=80 --type=NodePort
service/nginx exposed

# 查看服务状态
[root@k8s-master ~]# kubectl get pods,service
NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-6867cdf567-x4mvf   1/1     Running   0          75s

NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
service/kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        22m
service/nginx        NodePort    10.105.220.102   <none>        80:31730/TCP   60s

# 最后在电脑上访问部署的nginx服务

以上是关于K8s Kubernetes集群部署的主要内容,如果未能解决你的问题,请参考以下文章

高可用集群篇-- K8S快速入门及集群部署

k8s集群架构及基本操作

kubernetes系列03—kubeadm安装部署K8S集群

k8s 实践经验:认识 k8s

资深架构师分享:1 天落地的 Kubernetes 容器化方案

K8S简介+CentOS7 部署K8S集群