kubernetes-简单模式


使用kubeadm安装

通过vagrant的Vagrantfile新建三台主机

主机名 IP
master1 192.168.33.11
node1 192.168.33.12
node2 192.168.33.13

Vagrantfile

Vagrant.configure("2") do |config|

  config.vm.define "k8s-01" do |master|
    master.vm.box =  "centos-base"
    master.vm.provider "virtualbox" do |vb|
      vb.memory = "2048"
      vb.cpus = 2
    end
	master.vm.network "private_network", ip: "192.168.33.11", auto_config: true
    master.vm.hostname = "master1"
	master.vm.provision "shell", path: "./init.sh"
  end

  config.vm.define "k8s-02" do |node1|
    node1.vm.box =  "centos-base"
	node1.vm.network "private_network", ip: "192.168.33.12", auto_config: true
    node1.vm.hostname = "node1"
	node1.vm.provision "shell", path: "./init.sh"
  end

  config.vm.define "k8s-03" do |node2|
    node2.vm.box =  "centos-base"
	node2.vm.network "private_network", ip: "192.168.33.13", auto_config: true
    node2.vm.hostname = "node2" 
	node2.vm.provision "shell", path: "./init.sh"
  end

end

初始化脚本:

#!/bin/bash

echo "初始化yum源"
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo
yum makecache fast

echo "更新系统"
yum -y update

echo "时间同步"
timedatectl set-timezone Asia/Shanghai

echo "关闭防火墙"
systemctl stop firewalld 

echo "禁selinux"
sed -i 's/enforcing/disabled/' /etc/selinux/config
setenforce 0

echo "禁swap"
sed -ri 's/.*swap.*/#&/' /etc/fstab
swapoff -a 

echo '允许 iptables 检查桥接流量'
modprobe br_netfilter

echo '写入配置参数'
cat <> /etc/hosts < /etc/docker/daemon.json
{
  "registry-mirrors": ["https://f2q9sv8j.mirror.aliyuncs.com"],
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF


systemctl enable docker
systemctl daemon-reload
systemctl restart docker


echo 'kubernetes 安装'
cat < /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF
setenforce 0
yum install -y kubelet kubeadm kubectl
systemctl enable kubelet && systemctl start kubelet

主节点执行, 主节点初始化后会产生一段从节点join命令 复制后在从节点执行

master1:
kubeadm init --apiserver-advertise-address=192.168.33.11 --image-repository registry.aliyuncs.com/google_containers --kubernetes-version v1.23.3 --pod-network-cidr=10.244.0.0/16

node1 & node2
kubeadm join 192.168.33.11:6443 --token b4b3u4.0sffdr3p2akoszzn --discovery-token-ca-cert-hash sha256:f4dd5b9820f40aafb34219a23a79e0205ad768ce4dca2528b5c7e07f43ed573d

在主节点操作集群

export KUBECONFIG=/etc/kubernetes/admin.conf
kubectl get nodes

部署kube-flannel网络, 注意多网卡配置

kubectl apply -f kube-flannel.yml

测试

1. 创建Deployment
# 创建nginx配置文件
vim nginx-deployment.yaml
# 文件内容
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80
# 部署
kubectl apply -f nginx-deployment.yaml
部署后,我们查看deployment信息

# 查看所有节点信息
[root@master ~]# kubectl get pods
NAME                               READY   STATUS    RESTARTS   AGE
nginx-deployment-59c9f8dff-4n258   1/1     Running   0          20m
nginx-deployment-59c9f8dff-528g8   1/1     Running   0          20m

# 查看更详细的节点信息
[root@master ~]# kubectl get pods -o wide
NAME                               READY   STATUS    RESTARTS   AGE   IP           NODE    NOMINATED NODE   READINESS GATES
nginx-deployment-59c9f8dff-4n258   1/1     Running   0          21m   10.244.2.2   node2              
nginx-deployment-59c9f8dff-528g8   1/1     Running   0          21m   10.244.1.2   node1              
2. 曝露资源
发现deployment被分布在了node1和node2上,尝试曝露服务给Service

kubectl expose deployment nginx-deployment --port=80 --type=NodePort
查看曝露的服务,由此,可以开始外网访问了

[root@master ~]# kubectl get svc
NAME               TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)        AGE
kubernetes         ClusterIP   10.1.0.1              443/TCP        105m
nginx-deployment   NodePort    10.1.155.69           80:30373/TCP   25m
发现对外网曝露的端口是30373,我们可以使用NodePort:30373 进行访问了
  • 参考:
  • 利用Vagrant创建k8s集群
  • kubeadm安装前提
  • kubeadm安装

Minikube 安装

minikube start | minikube (k8s.io)

1. 安装docker

curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube

minikube start --force --driver=docker --image-mirror-country='cn' --image-repository='registry.cn-hangzhou.aliyuncs.com/google_containers' --listen-address=0.0.0.0

# 查看状态
minikube status

# 访问集群
minikube kubectl -- get po -A

# 简化命令
alias kubectl="minikube kubectl --"
kubectl get po -A

# 安装dashboard
minikube dashboard

http://192.168.33.10:41842/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/

# 解决外部无法访问
为 dashboard 添加外部访问代理,此处的 IP 为本地系统 IP:
kubectl proxy --port=41842 --address='192.168.33.10' --accept-hosts='^.*' &
通过 url: http://192.168.33.10:41842/api/v1/namespaces/kube-system/services/http:kubernetes-dashboard:/proxy/ 访问 dashboard。

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-plugin
       #image: flannelcni/flannel-cni-plugin:v1.0.1 for ppc64le and mips64le (dockerhub limitations may apply)
        image: rancher/mirrored-flannelcni-flannel-cni-plugin:v1.0.1
        command:
        - cp
        args:
        - -f
        - /flannel
        - /opt/cni/bin/flannel
        volumeMounts:
        - name: cni-plugin
          mountPath: /opt/cni/bin
      - name: install-cni
       #image: flannelcni/flannel:v0.16.3 for ppc64le and mips64le (dockerhub limitations may apply)
        image: rancher/mirrored-flannelcni-flannel:v0.16.3
        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: flannelcni/flannel:v0.16.3 for ppc64le and mips64le (dockerhub limitations may apply)
        image: rancher/mirrored-flannelcni-flannel:v0.16.3
        command:
        - /opt/bin/flanneld
        args:
        - --ip-masq
        - --kube-subnet-mgr
        # 多网卡
        - --iface=eth1
        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/
        - name: xtables-lock
          mountPath: /run/xtables.lock
      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
      - name: xtables-lock
        hostPath:
          path: /run/xtables.lock
          type: FileOrCreate