基于Docker-K8s的Web集群

周辰沛
2023-12-01

项目名称:基于Docker-K8s的Web集群
项目环境:Docker 20.10.5,CentOS 7.6 (7台 2核2G),Nginx 1.19.8,Ansible 2.9.18,NFS,Prometheus 2.0.0,Grafana 4.2.0
项目描述:
实现一个高可用的负载均衡器的Web服务器集群,使用Kubeadm搭建K8s集群,底层采用K8s管理的Docker集群来提供Web服务,大量使用容器来完成Web服务的扩展性、高可用性。
项目步骤:
1.规划设计整个集群的架构,前端使用Nginx做负载均衡器,后端使用K8s来实现Web容器负载均衡和高可用;
2.部署好Ansible服务器,在所有的机器之间配置SSH免密通道;编写好部署Nginx,NFS,K8s的脚本,编写Ansible的Playbook实现批量部署;
3.后端采用K8s来管理整个Docker集群,基于Kubeadm3个节点的K8s集群,总共启动10个容器来提供Web服务;
4.使用NFS服务为所有的Docker节点提供相同Web数据,实现数据一致性。所有的Docker Nginx容器使用PV,PVC与 数据卷、NFS融合,实现容器Web文件共享;再创建服务,类型为NodePort,达到暴露端口的目的;

**1,**ansible部署环境
免密通道

ssh-keygen -t ecdsa
ssh-copy-id -i ~/.ssh/id_ecdsa.pub 192.168.174.72		# master
ssh-copy-id -i ~/.ssh/id_ecdsa.pub 192.168.174.73		# node1
ssh-copy-id -i ~/.ssh/id_ecdsa.pub 192.168.174.94		# node2
ssh-copy-id -i ~/.ssh/id_ecdsa.pub 192.168.174.81		# nfs-server
ssh-copy-id -i ~/.ssh/id_ecdsa.pub 192.168.174.79		# load-balancer
ssh-copy-id -i ~/.ssh/id_ecdsa.pub 192.168.174.75		# prometheus

安装ansible

yum install epel-release -y
yum install ansible -y

配置主机清单/etc/ansible/hosts

vim /etc/ansible/hosts
[docker-kubeadm]
192.168.174.72
192.168.174.73
192.168.174.94
[nfs]
192.168.174.81
192.168.174.72
192.168.174.73
192.168.174.94
[loadbalancer]
192.168.174.79

ansible-playbook

vim ansible_playbook.yaml 

- hosts: docker-kubeadm
  remote_user: root
  tasks:
  - name: deploy kubeadm
    script: ~/install_kubeadm.sh

- hosts: loadbalancer
  remote_user: root
  tasks:
  - name: deploy nginx
    script: ~/onekey_install_nginx.sh

- hosts: nfs
  remote_user: root
  tasks:
  - name: install nfs-utils
    script: ~/install_nfs.sh

ansible-playbook ansible_playbook.yaml

一键部署k8s

vim install_kubeadm.sh

#!/bin/bash

# 卸载旧版本
yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine

yum install -y yum-utils

yum-config-manager \
            --add-repo \
                http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

yum install -y docker-ce docker-ce-cli containerd.io

systemctl start docker
systemctl enable docker

#配置 Docker 使用 systemd 作为默认 Cgroup 驱动
cat <<EOF > /etc/docker/daemon.json
{
   "exec-opts": ["native.cgroupdriver=systemd"],
   "registry-mirrors" : [
    "https://registry.docker-cn.com",
    "https://docker.mirrors.ustc.edu.cn",
    "http://hub-mirror.c.163.com",
    "https://cr.console.aliyun.com/"]
}
EOF

#重启docker
systemctl restart docker

#关闭swap分区
swapoff -a # 临时
sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab # 永久
# 修改主机名后使用su - root 重新登录
# su - root
cat >> /etc/hosts << EOF 
192.168.174.72 master
192.168.174.73 node1
192.168.174.94 node2
EOF

#添加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 --now kubelet
#关闭防火墙
systemctl stop  firewalld
systemctl disable  firewalld
#关闭selinux
setenforce 0   #临时关闭
#永久关闭
sed -i  '/^SELINUX/ s/enforcing/disabled/' /etc/selinux/config

使用脚本一键安装nginx
脚本(博客地址):https://blog.csdn.net/a236542112478/article/details/120062556
安装nfs

vim install_nfs.sh 

#!/bin/bash
  
yum install nfs-utils -y
service nfs-server start
systemctl enable nfs-server

setenforce 0
sed -i '/^SELINUX=/ s/enforcing/disabled/' /etc/sysconfig/selinux
service firewalld stop
systemctl disable firewalld

2,部署K8s

kubeadm init \
--apiserver-advertise-address=192.168.174.72 \
--image-repository registry.aliyuncs.com/google_containers \
--service-cidr=10.1.0.0/16 \
--pod-network-cidr=10.244.0.0/16

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

加入node节点
安装网络插件

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

kubectl apply -f kube-flannel.yml

配置nfs

vim /etc/exports

/data  192.168.174.0/24(rw,no_root_squash,no_all_squash,sync)
mkdir /data/
chmod 777 /data/
service nfs-server restart
exportfs -rv
systemctl enable nfs-server
echo "hello,world" >>/data/index.html

PV、PVC与NFS融合

mkdir pv-pvc-pod-nfs
cd pv-pvc-pod-nfs/

PV-持久卷

vim pv-nfs.yaml

apiVersion: v1
kind: PersistentVolume	#资源类型
metadata:
  name: cl-nginx-pv
  labels:
    type: cl-nginx-pv
spec:
  capacity:
    storage: 5Gi
  accessModes:
    - ReadWriteMany		#访问模式,多个客户端读写
  persistentVolumeReclaimPolicy: Recycle	#回收策略-可以回收
  storageClassName: nfs						#注:指定存储卷的类型
  nfs:
    path: "/data"
    server: 192.168.174.81 #k8s-nfs
    readOnly: false		#不是只读

PVC-持久卷消费者

vim pvc-nfs.yaml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: cl-nginx-pvc
spec:
  accessModes:
  - ReadWriteMany
  resources:
     requests:
       storage: 1Gi
  storageClassName: nfs

deployment起pod

vim new-pod-nginx.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend-nginx
spec:
  replicas: 10
  selector:
    matchLabels:
      app: cl
      tier: backend-nginx
      track: stable
  template:
    metadata:
      labels:
        app: cl
        tier: backend-nginx
        track: stable
    spec:
      containers:
        - name: cl-pv-container-nfs
          image: nginx
          ports:
            - containerPort: 80
              
          volumeMounts:
            - mountPath: "/usr/share/nginx/html"
              name: cl-pv-storage-nfs
      volumes:
      - name: cl-pv-storage-nfs
        persistentVolumeClaim:
            claimName: cl-nginx-pvc

创建PV-持久卷、PVC-持久卷消费者、使用deployment起pod

kubectl apply -f pv-nfs.yaml
kubectl apply -f pvc-nfs.yaml
kubectl apply -f new-pod-nginx.yaml

master主机 - 暴露服务端口

kubectl expose deployment/backend-nginx --type="NodePort" --port 80

配置Loadbalancer
Loadbalancer 192.168.174.79

vim /usr/local/nginx/conf/nginx.conf

……
    upstream myweb {
        server 192.168.174.72:端口略;
        server 192.168.174.73:……;
        server 192.168.174.94:……;
    }
    server {
        listen       80;
        server_name  www.cl.com;
        
        location / {
            proxy_pass  http://myweb;
        }
……

 类似资料: