Kubernetes集群环境搭建(简单易懂)

本次Kubernetes集群环境搭建使用的是一主两从的环境,即一个master节点和两个node节点。

目录

前期准备

master节点执行

node节点执行

安装flannel网络插件

查看集群状态


前期准备

准备好三台虚拟机。

硬件环境的要求

  • CPU:2核
  • Memory:2G

软件环境的要求

使用CentOS 7版本的操作系统。

[root@localhost ~]# cat /etc/centos-release
CentOS Linux release 7.9.2009 (Core)

1、Docker环境准备

# 关闭防火墙
systemctl stop firewalld
systemctl disable firewalld

# 关闭selinux
setenforce 0   # 临时关闭
# 永久关闭
vim /etc/selinux/config
SELINUX=disabled    # 将enforcing改为disabled

2、安装Docker

1.卸载旧的版本
yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
                  
2.需要的安装包
yum install yum-utils -y

3.设置镜像的仓库
# 镜像仓库默认是国外的,建议安装国内的较好
yum-config-manager \
    --add-repo \
    http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 
    
4.安装docker ——Install Docker Engine
# docker-ce 社区版  docker-ee 企业版
yum install docker-ce docker-ce-cli containerd.io -y

5.启动docker
systemctl start docker

6.设置docker开机自启
systemctl enable docker

3、配置Docker使用systemd作为默认Cgroup驱动

[root@master ~]# vim /etc/docker/daemon.json
{
   "exec-opts": ["native.cgroupdriver=systemd"]
}

# 刷新docker服务
systemctl restart docker

4、关闭swap交换分区

# 临时关闭
swapoff -a

# 永久关闭
[root@master ~]# vim /etc/fstab
#/dev/mapper/cl-swap     swap                    swap    defaults        0 0
将该行注释

5、重新命名主机

hostnamectl set-hostname master
hostnamectl set-hostname node1
hostnamectl set-hostname node2

修改主机名后使用 su 或 su - root 重新登录

6、在所有主机上修改hosts文件

方法一
[root@master ~]# vim /etc/hosts
# 在文件末尾添加这三行
192.168.58.140 master
192.168.58.141 node1
192.168.58.142 node2

方法二
[root@master ~]# cat >> /etc/hosts << EOF     追加输出重定向到/etc/hosts文件中
192.168.58.140 master
192.168.58.141 node1
192.168.58.142 node2
EOF

7、安装 kubeadm、kubectl、kubelet

添加kubernetes yum软件源
[root@master ~]# cd /etc/yum.repos.d
[root@master yum.repos.d]# vim 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.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
跨服务器拷贝文件,让所有主机都添加上kubernetes yum软件源
[root@master yum.repos.d]# scp kubernetes.repo 192.168.58.141:/etc/yum.repos.d/
[root@master yum.repos.d]# scp kubernetes.repo 192.168.58.142:/etc/yum.repos.d/
安装kubeadm,kubelet和kubectl
[root@master ~]# yum install kubeadm kubelet kubectl -y

设置kubelet开机自启
[root@master ~]# systemctl enable kubelet

master节点执行

部署Kubernetes Master
 
提前准备coredns/coredns:1.8.4镜像,需要在每台机器上安装
[root@master ~]# docker pull coredns/coredns:1.8.4
[root@master ~]# docker tag coredns/coredns:1.8.4 registry.aliyuncs.com/google_containers/coredns:v1.8.4

初始化Kubernetes集群
[root@master ~]# kubeadm init \
--apiserver-advertise-address=192.168.58.140 \
--image-repository registry.aliyuncs.com/google_containers \
--service-cidr=10.1.0.0/16 \
--pod-network-cidr=10.244.0.0/16

# 这里的192.168.58.140是master的ip地址

执行成功效果如下:

......
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

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.58.140:6443 --token nu7d9c.pw3lc3p6qw54w2h7 \
	--discovery-token-ca-cert-hash sha256:d8761ef304e8748e39c9a4efabca6d561cf8faa38b8224c4034f4b6eb669d4ba

 按照相关提示在master节点上进行后续操作:

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

node节点执行

在node1主机和node2主机上执行以下命令:

kubeadm join 192.168.58.140:6443 --token nu7d9c.pw3lc3p6qw54w2h7 \
	--discovery-token-ca-cert-hash sha256:d8761ef304e8748e39c9a4efabca6d561cf8faa38b8224c4034f4b6eb669d4ba

执行成功效果如下:

[preflight] Running pre-flight checks
	[WARNING FileExisting-tc]: tc not found in system path
[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.

安装flannel网络插件

此处安装flannel网络插件,这里通过编写yaml文件来安装。

注意:flannel网络插件只需在 master节点 安装!

[root@master ~]# vim kube-flannel.yml
---
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: psp.flannel.unprivileged
  annotations:
    seccomp.security.alpha.kubernetes.io/allowedProfileNames: docker/default
    seccomp.security.alpha.kubernetes.io/defaultProfileName: docker/default
    apparmor.security.beta.kubernetes.io/allowedProfileNames: runtime/default
    apparmor.security.beta.kubernetes.io/defaultProfileName: runtime/default
spec:
  privileged: false
  volumes:
  - configMap
  - secret
  - emptyDir
  - hostPath
  allowedHostPaths:
  - pathPrefix: "/etc/cni/net.d"
  - pathPrefix: "/etc/kube-flannel"
  - pathPrefix: "/run/flannel"
  readOnlyRootFilesystem: false
  # Users and groups
  runAsUser:
    rule: RunAsAny
  supplementalGroups:
    rule: RunAsAny
  fsGroup:
    rule: RunAsAny
  # Privilege Escalation
  allowPrivilegeEscalation: false
  defaultAllowPrivilegeEscalation: false
  # Capabilities
  allowedCapabilities: ['NET_ADMIN', 'NET_RAW']
  defaultAddCapabilities: []
  requiredDropCapabilities: []
  # Host namespaces
  hostPID: false
  hostIPC: false
  hostNetwork: true
  hostPorts:
  - min: 0
    max: 65535
  # SELinux
  seLinux:
    # SELinux is unused in CaaSP
    rule: 'RunAsAny'
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: flannel
rules:
- apiGroups: ['extensions']
  resources: ['podsecuritypolicies']
  verbs: ['use']
  resourceNames: ['psp.flannel.unprivileged']
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
- apiGroups:
  - ""
  resources:
  - nodes
  verbs:
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - nodes/status
  verbs:
  - patch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: flannel
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: flannel
subjects:
- kind: ServiceAccount
  name: flannel
  namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: flannel
  namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
  name: kube-flannel-cfg
  namespace: kube-system
  labels:
    tier: node
    app: flannel
data:
  cni-conf.json: |
    {
      "name": "cbr0",
      "cniVersion": "0.3.1",
      "plugins": [
        {
          "type": "flannel",
          "delegate": {
            "hairpinMode": true,
            "isDefaultGateway": true
          }
        },
        {
          "type": "portmap",
          "capabilities": {
            "portMappings": true
          }
        }
      ]
    }
  net-conf.json: |
    {
      "Network": "10.244.0.0/16",
      "Backend": {
        "Type": "vxlan"
      }
    }
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: kube-flannel-ds
  namespace: kube-system
  labels:
    tier: node
    app: flannel
spec:
  selector:
    matchLabels:
      app: flannel
  template:
    metadata:
      labels:
        tier: node
        app: flannel
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/os
                operator: In
                values:
                - linux
      hostNetwork: true
      priorityClassName: system-node-critical
      tolerations:
      - operator: Exists
        effect: NoSchedule
      serviceAccountName: flannel
      initContainers:
      - name: install-cni
        image: quay.io/coreos/flannel:v0.13.1-rc2
        command:
        - cp
        args:
        - -f
        - /etc/kube-flannel/cni-conf.json
        - /etc/cni/net.d/10-flannel.conflist
        volumeMounts:
        - name: cni
          mountPath: /etc/cni/net.d
        - name: flannel-cfg
          mountPath: /etc/kube-flannel/
      containers:
      - name: kube-flannel
        image: quay.io/coreos/flannel:v0.13.1-rc2
        command:
        - /opt/bin/flanneld
        args:
        - --ip-masq
        - --kube-subnet-mgr
        resources:
          requests:
            cpu: "100m"
            memory: "50Mi"
          limits:
            cpu: "100m"
            memory: "50Mi"
        securityContext:
          privileged: false
          capabilities:
            add: ["NET_ADMIN", "NET_RAW"]
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        volumeMounts:
        - name: run
          mountPath: /run/flannel
        - name: flannel-cfg
          mountPath: /etc/kube-flannel/
      volumes:
      - name: run
        hostPath:
          path: /run/flannel
      - name: cni
        hostPath:
          path: /etc/cni/net.d
      - name: flannel-cfg
        configMap:
          name: kube-flannel-cfg

部署flannel插件

[root@master ~]# kubectl apply -f kube-flannel.yml
Warning: policy/v1beta1 PodSecurityPolicy is deprecated in v1.21+, unavailable in v1.25+
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

查看flannel是否安装成功并启动

[root@master ~]# ps aux|grep flannel
root       19238  4.5  1.8 1118456 34508 ?       Ssl  22:23   0:00 /opt/bin/flanneld --ip-masq --kube-subnet-mgr

查看集群状态

到此K8s集群基本是已经搭建完成了,后续只需等待node节点准备完毕,便会自动加入到集群中来。

[root@master ~]# kubectl get nodes
NAME     STATUS     ROLES                  AGE     VERSION
master   Ready      control-plane,master   3h28m   v1.22.1
node1    Ready      <none>                 173m    v1.22.1
node2    NotReady   <none>                 3m4s    v1.22.1

过一段时间,再次查看node节点会是Ready状态,大概需要十几分钟的时间
[root@master ~]# kubectl get nodes
NAME     STATUS   ROLES                  AGE     VERSION
master   Ready    control-plane,master   3h39m   v1.22.1
node1    Ready    <none>                 3h3m    v1.22.1
node2    Ready    <none>                 13m     v1.22.1

查看更详细的信息
[root@master ~]# kubectl get node -o wide
NAME     STATUS   ROLES                  AGE     VERSION   INTERNAL-IP      EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION          CONTAINER-RUNTIME
master   Ready    control-plane,master   8h      v1.22.1   192.168.58.140   <none>        CentOS Linux 8 (Core)   4.18.0-193.el8.x86_64   docker://20.10.8
node1    Ready    <none>                 7h43m   v1.22.1   192.168.58.141   <none>        CentOS Linux 8 (Core)   4.18.0-193.el8.x86_64   docker://20.10.8
node2    Ready    <none>                 4h53m   v1.22.1   192.168.58.143   <none>        CentOS Linux 8 (Core)   4.18.0-193.el8.x86_64   docker://20.10.8

也可以在master节点上查询flannel网络插件是否启动,使用相关命令查看一下 kube-system 命名空间启动的Pod的情况(所有由Kubernetes系统创建的资源都处于kube-system这个namespace中)。

[root@master ~]# kubectl get pod -n kube-system
NAME                             READY   STATUS    RESTARTS      AGE
coredns-7f6cbbb7b8-7n5vp         1/1     Running   3 (92m ago)   4h39m
coredns-7f6cbbb7b8-lhg54         1/1     Running   4 (92m ago)   4h39m
etcd-master                      1/1     Running   3 (92m ago)   4h39m
kube-apiserver-master            1/1     Running   3 (92m ago)   4h39m
kube-controller-manager-master   1/1     Running   4 (92m ago)   4h39m
kube-flannel-ds-scltj            1/1     Running   0             73m
kube-flannel-ds-t4kxz            1/1     Running   2 (91m ago)   4h3m
kube-flannel-ds-v4686            1/1     Running   3 (92m ago)   4h36m
kube-proxy-9xdp9                 1/1     Running   2 (91m ago)   4h3m
kube-proxy-hv8fd                 1/1     Running   3 (92m ago)   4h39m
kube-proxy-md7dr                 1/1     Running   0             73m
kube-scheduler-master            1/1     Running   3 (92m ago)   4h39m
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_SmallTownKid_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值