kubernetes 部署

kubernetes 部署

环境说明:

主机名ip系统
master192.168.58.110centos7
node01192.168.58.111centos7
node02192.168.58.125centos7

安装前准备

所有主机上都要做的

设置主机名:
# hostnamectl set-hostname <hostname> 
[root@master ~]#  hostnamectl set-hostname master(node01/node02)
[root@master ~]#  bash

#关闭防火墙
[root@master ~]# systemctl disable --now firewalld
#关闭Selinux
[root@master ~]# setenforce 0    
[root@master ~]# vim /etc/sysconfig/selinux 
SELINUX=disabled          #将此处改为disabled
[root@master ~]# iptables -F    #清空iptables规则

[root@master ~]# reboot
在master添加hosts:
# cat >> /etc/hosts << EOF
192.168.58.110 master master.example.com
192.168.58.111 node1 node1.example.com
192.168.58.125 node2 node2.example.com
EOF

#禁用swap交换分区
[root@master ~]# swapoff -a   #临时禁用swap
[root@master ~]# vim /etc/fstab     #打开自动挂载的配置文件,将swap配置项注释掉
#/dev/mapper/cl-swap     swap                    swap    defaults        0 0
#就注释掉上面那行
[root@master ~]# mount -a    #重新加载挂载的配置文件
[root@master ~]# free -h     #确认输出的swap行如下(都为0):
Swap:            0B          0B          0B


免密认证:
[root@master ~]# ssh-keygen -t rsa
[root@master ~]# ssh-copy-id master
[root@master ~]# ssh-copy-id node01
[root@master ~]# ssh-copy-id node02


时间同步:
[root@master ~]#  yum -y install chrony
[root@master ~]#  vim /etc/chrony.conf
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
pool time1.aliyun.com iburst  //添加此行
# Record the rate at which the system clock gains/losses time.
driftfile /var/lib/chrony/drift
........此处省略n行
[root@master ~]#  systemctl enable --now chronyd   // 自启动
[root@master ~]#  systemctl restart chronyd  //重载配置文件
[root@master ~]# for i in master node01 node02;do ssh $i 'date';done
2021年 12月 18日 星期六 15:40:06 CST
2021年 12月 18日 星期六 15:40:07 CST
2021年 12月 18日 星期六 15:40:07 CST

master主机上的准备工作

将桥接的IPv4流量传递到iptables的链:
# cat > /etc/sysctl.d/k8s.conf << EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
# sysctl --system  # 生效

安装过程:

所有节点安装Docker/kubeadm/kubelet

Kubernetes默认CRI(容器运行时)为Docker,因此先安装Docker。

所有主机安装docker

# wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo
# yum -y install docker-ce
# systemctl enable --now docker
# docker --version

//  "registry-mirrors": 中的连接需要个人的阿里云镜像加速链接 详细请参考本人 docker 基础用法

# cat > /etc/docker/daemon.json << EOF
{
  "registry-mirrors": ["https://a74l47xi.mirror.aliyuncs.com"],  
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF

#systemctl daemon-reload
#systemctl restart docker

配置kubernetes阿里云YUM软件源

# 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
所有主机安装kubeadm,kubelet和kubectl

由于版本更新频繁,也可指定版本号部署:

# yum install -y kubelet kubeadm kubectl
# systemctl enable kubelet
部署Kubernetes Master(仅在mster主机上执行)

在192.168.58.110(Master)执行。

# kubeadm init \
  --apiserver-advertise-address=192.168.58.110 \   //此处填写maser主机ip
  --image-repository registry.aliyuncs.com/google_containers \  此处用的aliyun镜像
  --kubernetes-version v1.23.1 \  //此处,版本跟随安装的版本发生变化
  --service-cidr=10.96.0.0/12 \    // 此处保持默认,为官方ip
  --pod-network-cidr=10.244.0.0/16  // 此处保持默认,为官方ip

由于默认拉取镜像地址k8s.gcr.io国内无法访问,这里指定阿里云镜像仓库地址。

[root@master ~]# kubeadm init \
> --apiserver-advertise-address=192.168.58.110 \
> --image-repository registry.aliyuncs.com/google_containers \
> --kubernetes-version v1.23.1 \
> --service-cidr=10.96.0.0/12 \
> --pod-network-cidr=10.244.0.0/16
[init] Using Kubernetes version: v1.23.1
[preflight] Running pre-flight checks
[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'


..........此处省略n行

// 等待3-5分钟,出现以下命令即为成功

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.110:6443 --token 9ulqab.wlggx689zw4ll33h \
    --discovery-token-ca-cert-hash sha256:9316560df620b760e8114802a230795d88348d4122792cb8fd67b3e4af4e2ba9 

// 将此处的集群命令保存好,如以后需要添加工作节点时,则会使用到此命令
[root@master ~]# vim init
kubeadm join 192.168.58.110:6443 --token 9ulqab.wlggx689zw4ll33h \
    --discovery-token-ca-cert-hash sha256:9316560df620b760e8114802a230795d88348d4122792cb8fd67b3e4af4e2ba9 


环境变量

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

查看集群状态

[root@master ~]# kubectl get nodes
NAME     STATUS     ROLES                  AGE    VERSION
master   NotReady   control-plane,master   3m4s   v1.23.1

将node01及node02加入集群
# node01

[root@node01 ~]# kubeadm join 192.168.58.110:6443 --token 9ulqab.wlggx689zw4ll33h \
>     --discovery-token-ca-cert-hash sha256:9316560df620b760e8114802a230795d88348d4122792cb8fd67b3e4af4e2ba9 
[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 SystemVerification]: this Docker version is not on the list of validated versions: 20.10.12. Latest validated version: 19.03
[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.

#node02

[root@node02 ~]# kubeadm join 192.168.58.110:6443 --token 9ulqab.wlggx689zw4ll33h \
>     --discovery-token-ca-cert-hash sha256:9316560df620b760e8114802a230795d88348d4122792cb8fd67b3e4af4e2ba9 
[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 SystemVerification]: this Docker version is not on the list of validated versions: 20.10.12. Latest validated version: 19.03
[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.

使用kubctl get node查看集群状态

[root@master ~]# kubectl get nodes    //此时发现有三台主机
NAME     STATUS     ROLES                  AGE     VERSION
master   NotReady   control-plane,master   5m23s   v1.23.1
node01   NotReady   <none>                 23s     v1.23.1
node02   NotReady   <none>                 18s     v1.23.1


安装Pod网络插件(CNI)(仅master主机上安装便可)
# kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

如果上面命令因网络原因则可以将flannel官方yml文件内容复制到master主机上的yml文件中,使用 kubectl apply -f 指定文件执行,如下:

[root@master ~]# vi kube-flannel.yml  //注意在编辑文件时,此处应使用vi(vi 复制粘贴是保持文本的 格式而vim 则会有所改变)
---
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-plugin
        image: rancher/mirrored-flannelcni-flannel-cni-plugin:v1.0.0
        command:
        - cp
        args:
        - -f
        - /flannel
        - /opt/cni/bin/flannel
        volumeMounts:
        - name: cni-plugin
          mountPath: /opt/cni/bin
      - name: install-cni
        image: quay.io/coreos/flannel:v0.15.1
        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.15.1
        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-plugin
        hostPath:
          path: /opt/cni/bin
      - name: cni
        hostPath:
          path: /etc/cni/net.d
      - name: flannel-cfg
        configMap:
          name: kube-flannel-cfg


[root@master ~]# ls
anaconda-ks.cfg    init  kube-flannel.yml  

[root@master ~]# 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@master ~]# kubectl get nodes
NAME     STATUS     ROLES                  AGE   VERSION
master   NotReady   control-plane,master   17m   v1.20.0
node01   NotReady   <none>                 94s   v1.20.0
node02   NotReady   <none>                 89s   v1.20.0

此时我们需要等待master、node01、node02主机拉取镜像完成,就绪完成即可。大概等待(5-7分钟)

NAME     STATUS   ROLES                  AGE   VERSION
master   Ready    control-plane,master   54m   v1.20.0
node01   Ready    <none>                 38m   v1.20.0
node02   Ready    <none>                 38m   v1.20.0

## 当集群中的所有主机都为ready状态时Kubernetes集群就算部署完成了

测试kubernetes集群

在Kubernetes集群中创建一个pod,验证是否正常运行:

[root@master ~]# kubectl create deployment nginx --image=nginx  // 使用nginx 镜像运行一个pod
deployment.apps/nginx created

[root@master ~]# kubectl expose deployment nginx --port=80 --type=NodePort  //为指定的pod暴露端口
service/nginx exposed

[root@master ~]# kubectl get pods // 查看pod状态
NAME                     READY   STATUS              RESTARTS   AGE
nginx-6799fc88d8-rhvwk   0/1     ContainerCreating   0          13s

[root@master ~]# kubectl get pod,svc // 查看指定的pod、server服务的状态
NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-6799fc88d8-rhvwk   1/1     Running   0          4m36s

NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
service/kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        61m
service/nginx        NodePort    10.105.202.218   <none>        80:31129/TCP   4m29s

## 此处nginx server的80端口映射在主机的31129上,所以我们需要在主机上使用master的ip+31129 访问

访问测试
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值