安装 Kubernetes

如果您选择 K8s 的方式部署 PolarDB-X,需要前置安装 Kubernetes 集群。Kubernetes 支持多种安装方式,您可以选择 Kubernetes 官方文档 提供的方式进行部署,也可以直接使用阿里云的 容器服务(ACK) 提供的 Kubernetes 集群。

本文档将基于 kubeadm 工具,介绍如何安装一个 Kubernetes 集群。

基于 kubeadm 安装 Kubernetes

推荐从阿里云镜像仓库安装 Kubernetes 组件,推荐安装 v1.21.0 或更高版本。 Kubernetes 的容器镜像必须与安装 Kubernetes 组件时选择的版本保持一致,如果选择安装 v1.21.0 之外的 Kubernetes 版本,则必须参考文档准备相关镜像。

准备工作

配置 Yum 仓库

在部署机(ops)上编辑 kubernetes.repo 配置文件:

vi $HOME/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

如果部署环境是阿里云 ECS 服务器,且未接入互联网,应该使用以下配置文件内容:

提示:https://mirrors.aliyun.com/ 应替换成内网域名 http://mirrors.cloud.aliyuncs.com/

[kubernetes]
name=Kubernetes
baseurl=http://mirrors.cloud.aliyuncs.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=http://mirrors.cloud.aliyuncs.com/kubernetes/yum/doc/yum-key.gpg http://mirrors.cloud.aliyuncs.com/kubernetes/yum/doc/rpm-package-key.gpg

复制配置文件到所有服务器:

ansible -i ${ini_file} all -m synchronize -a " src=$HOME/kubernetes.repo dest=/etc/yum.repos.d/ " -u root

目录映射

Docker 的数据目录在 /var/lib/docker 下,存放镜像相关的文件。Kubernetes 在目录 /var/lib/kubelet 存放容器相关文件,推荐将这两个目录软链接到数据盘。执行如下命令,完成两个目录软链操作:

ansible -i ${ini_file} all -m shell -a " mkdir -p /polarx/kubelet"
ansible -i ${ini_file} all -m shell -a " ln -s /polarx/kubelet /var/lib/kubelet "
ansible -i ${ini_file} all -m shell -a " mkdir -p /polarx/docker "
ansible -i ${ini_file} all -m shell -a " ln -s /polarx/docker /var/lib/docker "

配置 Docker

编辑 daemon.json 文件,添加您的私有镜像仓库地址到 insecure-registries 列表中,以便使用 HTTP 访问。此处以 registry:5000 为例进行说明,您可以修改成对应的私有仓库地址。

vi $HOME/daemon.json

输入内容:

{ 
  "exec-opts": ["native.cgroupdriver=systemd"],
  "insecure-registries": ["registry:5000"]
}

复制 daemon.json 文件到所有服务器:

ansible -i ${ini_file} all -m synchronize -a " src=$HOME/daemon.json dest=/etc/docker/daemon.json " -u root

重启 Docker 服务:

ansible -i ${ini_file} all -m shell -a " systemctl restart docker "

检查 Docker 服务是否在重启后正常运行:

ansible -i ${ini_file} all -m shell -a " systemctl status docker | grep Active "

安装 Kubernetes

软件安装

批量安装 Kubernetes 及组件:

ansible -i ${ini_file} all -m shell -a " yum install --nogpgcheck -y kubelet-1.21.0 kubeadm-1.21.0 kubectl-1.21.0 "

启动主节点

选择一台服务器作为 Kubernetes 主节点(master),用 ssh 命令登录:

ssh 192.168.1.105

运行 kubeadm 命令,指定私有镜像仓库地址:

kubeadm init --image-repository=registry:5000 --kubernetes-version=v1.21.0  \
        --pod-network-cidr=10.244.0.0/16 --v=5

启动成功后,应该有下列输出:

Your Kubernetes control-plane has initialized successfully!

...

Then you can join any number of worker nodes by running the following on each as root:

kubeadm join 192.168.1.105:6443 --token wgdbhh.gg93lod64h7u722s \
        --discovery-token-ca-cert-hash sha256:4d88e3b1bec75ce6d0ac011a0c94a01feaa6144682763db9fcaa69adbcd42de5

添加工作节点

用 ssh 命令登录另一台服务器:

ssh 192.168.1.102

运行启动主节点(master)提供的 kubeadm join 命令,添加工作节点到 Kubernetes 集群:

kubeadm join 192.168.1.105:6443 --token wgdbhh.gg93lod64h7u722s \
        --discovery-token-ca-cert-hash sha256:4d88e3b1bec75ce6d0ac011a0c94a01feaa6144682763db9fcaa69adbcd42de5

添加主节点

为保证生产环境 Kubernetes 集群的高可用,建议在集群内部署多个主节点(master)。 同样,用 ssh 命令登录 192.168.1.106 :

ssh 192.168.1.106

加入新的主节点只需要前面启动主节点(master)提供的 kubeadm join 命令后添加 --control-plane 参数:

kubeadm join 192.168.1.105:6443 --token wgdbhh.gg93lod64h7u722s \
        --discovery-token-ca-cert-hash sha256:4d88e3b1bec75ce6d0ac011a0c94a01feaa6144682763db9fcaa69adbcd42de5 \
        --control-plane

重新生成 Token

启动主节点(master)提供的 kubeadm join 命令的 token 存在有效期,如果添加节点时提示 token 失效,可以通过以下方式重新生成:

kubeadm token create

查询创建的 token:

kubeadm token list

输出 token list 内容示例:

TOKEN                     TTL         EXPIRES                     USAGES                   DESCRIPTION                                                EXTRA GROUPS
j47bwk.sz2lv16rbtlhx9ge   23h         2023-03-08T18:40:11+08:00   authentication,signing   <none>                                                     system:bootstrappers:kubeadm:default-node-token

使用输出的 TOKEN 取代原 kubeadm join 命令的 --token 参数:

kubeadm join 192.168.1.105:6443 --token j47bwk.sz2lv16rbtlhx9ge \
        --discovery-token-ca-cert-hash sha256:4d88e3b1bec75ce6d0ac011a0c94a01feaa6144682763db9fcaa69adbcd42de5

这样,可以再次向 Kubernetes 集群添加节点。

配置 kubectl

在部署机(ops)安装 kubectl 客户端:

yum install kubectl-1.21.0 -y

使用 kubectl 访问 Kubernetes 集群,需要配置 $HOME/.kube/config 文件。 最简便的配置方式是从 Kubernetes 主节点复制配置文件到上述位置:

mkdir $HOME/.kube
scp 192.168.1.105:/etc/kubernetes/admin.conf $HOME/.kube/config

批量复制 kubectl 配置文件到其他服务器:

ansible -i ${ini_file} all -m shell -a " mkdir -p \$HOME/.kube " 
ansible -i ${ini_file} all -m synchronize -a " src=$HOME/.kube/config dest=\$HOME/.kube/config "

检查部署机(ops)是否可以访问 Kubernetes 集群:

kubectl get nodes -o wide

配置容器网络

在安装容器网络前,Kubernetes 集群无法正常工作。 容器网络的解决方案有多个选项,这里仅介绍基本 calico 网络的安装方式。

编辑配置文件

创建 Yaml 配置文件:

vi calico_v3.15.1.yaml

内容为:

---
# Source: calico/templates/calico-config.yaml
# This ConfigMap is used to configure a self-hosted Calico installation.
kind: ConfigMap
apiVersion: v1
metadata:
  name: calico-config
  namespace: kube-system
data:
  # Typha is disabled.
  typha_service_name: "none"
  # Configure the backend to use.
  calico_backend: "bird"

  # Configure the MTU to use
  veth_mtu: "1440"

  # The CNI network configuration to install on each node.  The special
  # values in this config will be automatically populated.
  cni_network_config: |-
    {
      "name": "k8s-pod-network",
      "cniVersion": "0.3.1",
      "plugins": [
        {
          "type": "calico",
          "log_level": "info",
          "datastore_type": "kubernetes",
          "nodename": "__KUBERNETES_NODE_NAME__",
          "mtu": __CNI_MTU__,
          "ipam": {
              "type": "calico-ipam"
          },
          "policy": {
              "type": "k8s"
          },
          "kubernetes": {
              "kubeconfig": "__KUBECONFIG_FILEPATH__"
          }
        },
        {
          "type": "portmap",
          "snat": true,
          "capabilities": {"portMappings": true}
        }
      ]
    }

---
# Source: calico/templates/kdd-crds.yaml
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: felixconfigurations.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: FelixConfiguration
    plural: felixconfigurations
    singular: felixconfiguration
---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: ipamblocks.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: IPAMBlock
    plural: ipamblocks
    singular: ipamblock

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: blockaffinities.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: BlockAffinity
    plural: blockaffinities
    singular: blockaffinity

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: ipamhandles.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: IPAMHandle
    plural: ipamhandles
    singular: ipamhandle

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: ipamconfigs.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: IPAMConfig
    plural: ipamconfigs
    singular: ipamconfig

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: bgppeers.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: BGPPeer
    plural: bgppeers
    singular: bgppeer

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: bgpconfigurations.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: BGPConfiguration
    plural: bgpconfigurations
    singular: bgpconfiguration

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: ippools.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: IPPool
    plural: ippools
    singular: ippool

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: hostendpoints.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: HostEndpoint
    plural: hostendpoints
    singular: hostendpoint

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: clusterinformations.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: ClusterInformation
    plural: clusterinformations
    singular: clusterinformation

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: globalnetworkpolicies.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: GlobalNetworkPolicy
    plural: globalnetworkpolicies
    singular: globalnetworkpolicy

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: globalnetworksets.crd.projectcalico.org
spec:
  scope: Cluster
  group: crd.projectcalico.org
  version: v1
  names:
    kind: GlobalNetworkSet
    plural: globalnetworksets
    singular: globalnetworkset

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: networkpolicies.crd.projectcalico.org
spec:
  scope: Namespaced
  group: crd.projectcalico.org
  version: v1
  names:
    kind: NetworkPolicy
    plural: networkpolicies
    singular: networkpolicy

---

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: networksets.crd.projectcalico.org
spec:
  scope: Namespaced
  group: crd.projectcalico.org
  version: v1
  names:
    kind: NetworkSet
    plural: networksets
    singular: networkset

---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  annotations:
    controller-gen.kubebuilder.io/version: (devel)
  name: kubecontrollersconfigurations.crd.projectcalico.org
spec:
  group: crd.projectcalico.org
  names:
    kind: KubeControllersConfiguration
    listKind: KubeControllersConfigurationList
    plural: kubecontrollersconfigurations
    singular: kubecontrollersconfiguration
  scope: Cluster
  versions:
    - name: v1
      schema:
        openAPIV3Schema:
          properties:
            apiVersion:
              description: 'APIVersion defines the versioned schema of this representation
              of an object. Servers should convert recognized schemas to the latest
              internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources'
              type: string
            kind:
              description: 'Kind is a string value representing the REST resource this
              object represents. Servers may infer this from the endpoint the client
              submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
              type: string
            metadata:
              type: object
            spec:
              description: KubeControllersConfigurationSpec contains the values of the
                Kubernetes controllers configuration.
              properties:
                controllers:
                  description: Controllers enables and configures individual Kubernetes
                    controllers
                  properties:
                    namespace:
                      description: Namespace enables and configures the namespace controller.
                        Enabled by default, set to nil to disable.
                      properties:
                        reconcilerPeriod:
                          description: 'ReconcilerPeriod is the period to perform reconciliation
                          with the Calico datastore. [Default: 5m]'
                          type: string
                      type: object
                    node:
                      description: Node enables and configures the node controller.
                        Enabled by default, set to nil to disable.
                      properties:
                        hostEndpoint:
                          description: HostEndpoint controls syncing nodes to host endpoints.
                            Disabled by default, set to nil to disable.
                          properties:
                            autoCreate:
                              description: 'AutoCreate enables automatic creation of
                              host endpoints for every node. [Default: Disabled]'
                              type: string
                          type: object
                        reconcilerPeriod:
                          description: 'ReconcilerPeriod is the period to perform reconciliation
                          with the Calico datastore. [Default: 5m]'
                          type: string
                        syncLabels:
                          description: 'SyncLabels controls whether to copy Kubernetes
                          node labels to Calico nodes. [Default: Enabled]'
                          type: string
                      type: object
                    policy:
                      description: Policy enables and configures the policy controller.
                        Enabled by default, set to nil to disable.
                      properties:
                        reconcilerPeriod:
                          description: 'ReconcilerPeriod is the period to perform reconciliation
                          with the Calico datastore. [Default: 5m]'
                          type: string
                      type: object
                    serviceAccount:
                      description: ServiceAccount enables and configures the service
                        account controller. Enabled by default, set to nil to disable.
                      properties:
                        reconcilerPeriod:
                          description: 'ReconcilerPeriod is the period to perform reconciliation
                          with the Calico datastore. [Default: 5m]'
                          type: string
                      type: object
                    workloadEndpoint:
                      description: WorkloadEndpoint enables and configures the workload
                        endpoint controller. Enabled by default, set to nil to disable.
                      properties:
                        reconcilerPeriod:
                          description: 'ReconcilerPeriod is the period to perform reconciliation
                          with the Calico datastore. [Default: 5m]'
                          type: string
                      type: object
                  type: object
                etcdV3CompactionPeriod:
                  description: 'EtcdV3CompactionPeriod is the period between etcdv3
                  compaction requests. Set to 0 to disable. [Default: 10m]'
                  type: string
                healthChecks:
                  description: 'HealthChecks enables or disables support for health
                  checks [Default: Enabled]'
                  type: string
                logSeverityScreen:
                  description: 'LogSeverityScreen is the log severity above which logs
                  are sent to the stdout. [Default: Info]'
                  type: string
              required:
                - controllers
              type: object
            status:
              description: KubeControllersConfigurationStatus represents the status
                of the configuration. It's useful for admins to be able to see the actual
                config that was applied, which can be modified by environment variables
                on the kube-controllers process.
              properties:
                environmentVars:
                  additionalProperties:
                    type: string
                  description: EnvironmentVars contains the environment variables on
                    the kube-controllers that influenced the RunningConfig.
                  type: object
                runningConfig:
                  description: RunningConfig contains the effective config that is running
                    in the kube-controllers pod, after merging the API resource with
                    any environment variables.
                  properties:
                    controllers:
                      description: Controllers enables and configures individual Kubernetes
                        controllers
                      properties:
                        namespace:
                          description: Namespace enables and configures the namespace
                            controller. Enabled by default, set to nil to disable.
                          properties:
                            reconcilerPeriod:
                              description: 'ReconcilerPeriod is the period to perform
                              reconciliation with the Calico datastore. [Default:
                              5m]'
                              type: string
                          type: object
                        node:
                          description: Node enables and configures the node controller.
                            Enabled by default, set to nil to disable.
                          properties:
                            hostEndpoint:
                              description: HostEndpoint controls syncing nodes to host
                                endpoints. Disabled by default, set to nil to disable.
                              properties:
                                autoCreate:
                                  description: 'AutoCreate enables automatic creation
                                  of host endpoints for every node. [Default: Disabled]'
                                  type: string
                              type: object
                            reconcilerPeriod:
                              description: 'ReconcilerPeriod is the period to perform
                              reconciliation with the Calico datastore. [Default:
                              5m]'
                              type: string
                            syncLabels:
                              description: 'SyncLabels controls whether to copy Kubernetes
                              node labels to Calico nodes. [Default: Enabled]'
                              type: string
                          type: object
                        policy:
                          description: Policy enables and configures the policy controller.
                            Enabled by default, set to nil to disable.
                          properties:
                            reconcilerPeriod:
                              description: 'ReconcilerPeriod is the period to perform
                              reconciliation with the Calico datastore. [Default:
                              5m]'
                              type: string
                          type: object
                        serviceAccount:
                          description: ServiceAccount enables and configures the service
                            account controller. Enabled by default, set to nil to disable.
                          properties:
                            reconcilerPeriod:
                              description: 'ReconcilerPeriod is the period to perform
                              reconciliation with the Calico datastore. [Default:
                              5m]'
                              type: string
                          type: object
                        workloadEndpoint:
                          description: WorkloadEndpoint enables and configures the workload
                            endpoint controller. Enabled by default, set to nil to disable.
                          properties:
                            reconcilerPeriod:
                              description: 'ReconcilerPeriod is the period to perform
                              reconciliation with the Calico datastore. [Default:
                              5m]'
                              type: string
                          type: object
                      type: object
                    etcdV3CompactionPeriod:
                      description: 'EtcdV3CompactionPeriod is the period between etcdv3
                      compaction requests. Set to 0 to disable. [Default: 10m]'
                      type: string
                    healthChecks:
                      description: 'HealthChecks enables or disables support for health
                      checks [Default: Enabled]'
                      type: string
                    logSeverityScreen:
                      description: 'LogSeverityScreen is the log severity above which
                      logs are sent to the stdout. [Default: Info]'
                      type: string
                  required:
                    - controllers
                  type: object
              type: object
          type: object
      served: true
      storage: true  
---
# Source: calico/templates/rbac.yaml

# Include a clusterrole for the kube-controllers component,
# and bind it to the calico-kube-controllers serviceaccount.
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: calico-kube-controllers
rules:
  # Nodes are watched to monitor for deletions.
  - apiGroups: [""]
    resources:
      - nodes
    verbs:
      - watch
      - list
      - get
  # Pods are queried to check for existence.
  - apiGroups: [""]
    resources:
      - pods
    verbs:
      - get
  # IPAM resources are manipulated when nodes are deleted.
  - apiGroups: ["crd.projectcalico.org"]
    resources:
      - ippools
    verbs:
      - list
  - apiGroups: ["crd.projectcalico.org"]
    resources:
      - blockaffinities
      - ipamblocks
      - ipamhandles
      - hostendpoints
    verbs:
      - get
      - list
      - create
      - update
      - delete
  # Needs access to update clusterinformations.
  - apiGroups: ["crd.projectcalico.org"]
    resources:
      - clusterinformations
      - kubecontrollersconfigurations
    verbs:
      - get
      - create
      - update
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: calico-kube-controllers
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: calico-kube-controllers
subjects:
- kind: ServiceAccount
  name: calico-kube-controllers
  namespace: kube-system
---
# Include a clusterrole for the calico-node DaemonSet,
# and bind it to the calico-node serviceaccount.
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: calico-node
rules:
  # The CNI plugin needs to get pods, nodes, and namespaces.
  - apiGroups: [""]
    resources:
      - pods
      - nodes
      - namespaces
      - configmaps
    verbs:
      - get
  - apiGroups: [""]
    resources:
      - endpoints
      - services
    verbs:
      # Used to discover service IPs for advertisement.
      - watch
      - list
      # Used to discover Typhas.
      - get
  - apiGroups: [""]
    resources:
      - nodes/status
    verbs:
      # Needed for clearing NodeNetworkUnavailable flag.
      - patch
      # Calico stores some configuration information in node annotations.
      - update
  # Watch for changes to Kubernetes NetworkPolicies.
  - apiGroups: ["networking.k8s.io"]
    resources:
      - networkpolicies
    verbs:
      - watch
      - list
  # Used by Calico for policy information.
  - apiGroups: [""]
    resources:
      - pods
      - namespaces
      - serviceaccounts
    verbs:
      - list
      - watch
  # The CNI plugin patches pods/status.
  - apiGroups: [""]
    resources:
      - pods/status
    verbs:
      - patch
  # Calico monitors various CRDs for config.
  - apiGroups: ["crd.projectcalico.org"]
    resources:
      - globalfelixconfigs
      - felixconfigurations
      - bgppeers
      - globalbgpconfigs
      - bgpconfigurations
      - ippools
      - ipamblocks
      - globalnetworkpolicies
      - globalnetworksets
      - networkpolicies
      - networksets
      - clusterinformations
      - hostendpoints
    verbs:
      - get
      - list
      - watch
  # Calico must create and update some CRDs on startup.
  - apiGroups: ["crd.projectcalico.org"]
    resources:
      - ippools
      - felixconfigurations
      - clusterinformations
    verbs:
      - create
      - update
  # Calico stores some configuration information on the node.
  - apiGroups: [""]
    resources:
      - nodes
    verbs:
      - get
      - list
      - watch
  # These permissions are only requried for upgrade from v2.6, and can
  # be removed after upgrade or on fresh installations.
  - apiGroups: ["crd.projectcalico.org"]
    resources:
      - bgpconfigurations
      - bgppeers
    verbs:
      - create
      - update
  # These permissions are required for Calico CNI to perform IPAM allocations.
  - apiGroups: ["crd.projectcalico.org"]
    resources:
      - blockaffinities
      - ipamblocks
      - ipamhandles
    verbs:
      - get
      - list
      - create
      - update
      - delete
  - apiGroups: ["crd.projectcalico.org"]
    resources:
      - ipamconfigs
    verbs:
      - get
  # Block affinities must also be watchable by confd for route aggregation.
  - apiGroups: ["crd.projectcalico.org"]
    resources:
      - blockaffinities
    verbs:
      - watch
  # The Calico IPAM migration needs to get daemonsets. These permissions can be
  # removed if not upgrading from an installation using host-local IPAM.
  - apiGroups: ["apps"]
    resources:
      - daemonsets
    verbs:
      - get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: calico-node
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: calico-node
subjects:
- kind: ServiceAccount
  name: calico-node
  namespace: kube-system

---
# Source: calico/templates/calico-node.yaml
# This manifest installs the calico-node container, as well
# as the CNI plugins and network config on
# each master and worker node in a Kubernetes cluster.
kind: DaemonSet
apiVersion: apps/v1
metadata:
  name: calico-node
  namespace: kube-system
  labels:
    k8s-app: calico-node
spec:
  selector:
    matchLabels:
      k8s-app: calico-node
  updateStrategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
  template:
    metadata:
      labels:
        k8s-app: calico-node
      annotations:
        # This, along with the CriticalAddonsOnly toleration below,
        # marks the pod as a critical add-on, ensuring it gets
        # priority scheduling and that its resources are reserved
        # if it ever gets evicted.
        scheduler.alpha.kubernetes.io/critical-pod: ''
    spec:
      nodeSelector:
        beta.kubernetes.io/os: linux
      hostNetwork: true
      tolerations:
        # Make sure calico-node gets scheduled on all nodes.
        - effect: NoSchedule
          operator: Exists
        # Mark the pod as a critical add-on for rescheduling.
        - key: CriticalAddonsOnly
          operator: Exists
        - effect: NoExecute
          operator: Exists
      serviceAccountName: calico-node
      # Minimize downtime during a rolling upgrade or deletion; tell Kubernetes to do a "force
      # deletion": https://kubernetes.io/docs/concepts/workloads/pods/pod/#termination-of-pods.
      terminationGracePeriodSeconds: 0
      priorityClassName: system-node-critical
      initContainers:
        # This container performs upgrade from host-local IPAM to calico-ipam.
        # It can be deleted if this is a fresh installation, or if you have already
        # upgraded to use calico-ipam.
        - name: upgrade-ipam
          image: registry:5000/calico/cni:v3.15.1
          command: ["/opt/cni/bin/calico-ipam", "-upgrade"]
          env:
            - name: KUBERNETES_NODE_NAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            - name: CALICO_NETWORKING_BACKEND
              valueFrom:
                configMapKeyRef:
                  name: calico-config
                  key: calico_backend
          volumeMounts:
            - mountPath: /var/lib/cni/networks
              name: host-local-net-dir
            - mountPath: /host/opt/cni/bin
              name: cni-bin-dir
          securityContext:
            privileged: true
        # This container installs the CNI binaries
        # and CNI network config file on each node.
        - name: install-cni
          image: registry:5000/calico/cni:v3.15.1
          command: ["/install-cni.sh"]
          env:
            # Name of the CNI config file to create.
            - name: CNI_CONF_NAME
              value: "10-calico.conflist"
            # The CNI network config to install on each node.
            - name: CNI_NETWORK_CONFIG
              valueFrom:
                configMapKeyRef:
                  name: calico-config
                  key: cni_network_config
            # Set the hostname based on the k8s node name.
            - name: KUBERNETES_NODE_NAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            # CNI MTU Config variable
            - name: CNI_MTU
              valueFrom:
                configMapKeyRef:
                  name: calico-config
                  key: veth_mtu
            # Prevents the container from sleeping forever.
            - name: SLEEP
              value: "false"
          volumeMounts:
            - mountPath: /host/opt/cni/bin
              name: cni-bin-dir
            - mountPath: /host/etc/cni/net.d
              name: cni-net-dir
          securityContext:
            privileged: true
        # Adds a Flex Volume Driver that creates a per-pod Unix Domain Socket to allow Dikastes
        # to communicate with Felix over the Policy Sync API.
        - name: flexvol-driver
          image: registry:5000/calico/pod2daemon-flexvol:v3.15.1
          volumeMounts:
          - name: flexvol-driver-host
            mountPath: /host/driver
          securityContext:
            privileged: true
      containers:
        # Runs calico-node container on each Kubernetes node.  This
        # container programs network policy and routes on each
        # host.
        - name: calico-node
          image: registry:5000/calico/node:v3.15.1
          env:
            # Use Kubernetes API as the backing datastore.
            - name: DATASTORE_TYPE
              value: "kubernetes"
            # Wait for the datastore.
            - name: WAIT_FOR_DATASTORE
              value: "true"
            # Set based on the k8s node name.
            - name: NODENAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            # Choose the backend to use.
            - name: CALICO_NETWORKING_BACKEND
              valueFrom:
                configMapKeyRef:
                  name: calico-config
                  key: calico_backend
            # Cluster type to identify the deployment type
            - name: CLUSTER_TYPE
              value: "k8s,bgp"
            # Auto-detect the BGP IP address.
            - name: IP
              value: "autodetect"
            # Enable IPIP
            - name: CALICO_IPV4POOL_IPIP
              value: "Always"
            # Set MTU for tunnel device used if ipip is enabled
            - name: FELIX_IPINIPMTU
              valueFrom:
                configMapKeyRef:
                  name: calico-config
                  key: veth_mtu
            # The default IPv4 pool to create on startup if none exists. Pod IPs will be
            # chosen from this range. Changing this value after installation will have
            # no effect. This should fall within `--cluster-cidr`.
            - name: CALICO_IPV4POOL_CIDR
              value: "192.168.0.0/16"
            # Disable file logging so `kubectl logs` works.
            - name: CALICO_DISABLE_FILE_LOGGING
              value: "true"
            # Set Felix endpoint to host default action to ACCEPT.
            - name: FELIX_DEFAULTENDPOINTTOHOSTACTION
              value: "ACCEPT"
            # Disable IPv6 on Kubernetes.
            - name: FELIX_IPV6SUPPORT
              value: "false"
            # Set Felix logging to "info"
            - name: FELIX_LOGSEVERITYSCREEN
              value: "info"
            - name: FELIX_HEALTHENABLED
              value: "true"
          securityContext:
            privileged: true
          resources:
            requests:
              cpu: 250m
          livenessProbe:
            exec:
              command:
                - /bin/calico-node
                - -felix-live
                - -bird-live
            periodSeconds: 10
            initialDelaySeconds: 10
            failureThreshold: 6
          readinessProbe:
            exec:
              command:
              - /bin/calico-node
              - -bird-ready
              - -felix-ready
            periodSeconds: 10
          volumeMounts:
            - mountPath: /lib/modules
              name: lib-modules
              readOnly: true
            - mountPath: /run/xtables.lock
              name: xtables-lock
              readOnly: false
            - mountPath: /var/run/calico
              name: var-run-calico
              readOnly: false
            - mountPath: /var/lib/calico
              name: var-lib-calico
              readOnly: false
            - name: policysync
              mountPath: /var/run/nodeagent
      volumes:
        # Used by calico-node.
        - name: lib-modules
          hostPath:
            path: /lib/modules
        - name: var-run-calico
          hostPath:
            path: /var/run/calico
        - name: var-lib-calico
          hostPath:
            path: /var/lib/calico
        - name: xtables-lock
          hostPath:
            path: /run/xtables.lock
            type: FileOrCreate
        # Used to install CNI.
        - name: cni-bin-dir
          hostPath:
            path: /opt/cni/bin
        - name: cni-net-dir
          hostPath:
            path: /etc/cni/net.d
        # Mount in the directory for host-local IPAM allocations. This is
        # used when upgrading from host-local to calico-ipam, and can be removed
        # if not using the upgrade-ipam init container.
        - name: host-local-net-dir
          hostPath:
            path: /var/lib/cni/networks
        # Used to create per-pod Unix Domain Sockets
        - name: policysync
          hostPath:
            type: DirectoryOrCreate
            path: /var/run/nodeagent
        # Used to install Flex Volume Driver
        - name: flexvol-driver-host
          hostPath:
            type: DirectoryOrCreate
            path: /usr/libexec/kubernetes/kubelet-plugins/volume/exec/nodeagent~uds
---

apiVersion: v1
kind: ServiceAccount
metadata:
  name: calico-node
  namespace: kube-system

---
# Source: calico/templates/calico-kube-controllers.yaml

# See https://github.com/projectcalico/kube-controllers
apiVersion: apps/v1
kind: Deployment
metadata:
  name: calico-kube-controllers
  namespace: kube-system
  labels:
    k8s-app: calico-kube-controllers
spec:
  # The controllers can only have a single active instance.
  replicas: 1
  selector:
    matchLabels:
      k8s-app: calico-kube-controllers
  strategy:
    type: Recreate
  template:
    metadata:
      name: calico-kube-controllers
      namespace: kube-system
      labels:
        k8s-app: calico-kube-controllers
      annotations:
        scheduler.alpha.kubernetes.io/critical-pod: ''
    spec:
      nodeSelector:
        beta.kubernetes.io/os: linux
      tolerations:
        # Mark the pod as a critical add-on for rescheduling.
        - key: CriticalAddonsOnly
          operator: Exists
        - key: node-role.kubernetes.io/master
          effect: NoSchedule
      serviceAccountName: calico-kube-controllers
      priorityClassName: system-cluster-critical
      containers:
        - name: calico-kube-controllers
          image: registry:5000/calico/kube-controllers:v3.15.1
          env:
            # Choose which controllers to run.
            - name: ENABLED_CONTROLLERS
              value: node
            - name: DATASTORE_TYPE
              value: kubernetes
          readinessProbe:
            exec:
              command:
              - /usr/bin/check-status
              - -r

---

apiVersion: v1
kind: ServiceAccount
metadata:
  name: calico-kube-controllers
  namespace: kube-system
---
# Source: calico/templates/calico-etcd-secrets.yaml

---
# Source: calico/templates/calico-typha.yaml

---
# Source: calico/templates/configure-canal.yaml

配置 calico 网络

用 kubectl 命令应用配置文件:

kubectl apply -f calico_v3.15.1.yaml

检查 calico 容器是否创建:

kubectl -n kube-system get pods -o wide

耐心等待容器进入 Running 状态后,检查所有 Kubernetes 节点是否处于 "Ready":

kubectl get nodes -o wide

现在 Kubernetes 集群已经正常工作。

验证容器网络(可选)

推荐用 nginx 验证 Kubernetes 集群及容器网络是否正常工作。 首先需要在部署机(ops)下载 nginx 镜像,并上传到私有镜像仓库:

# 下载镜像
docker pull nginx:1.14.2

# 标记镜像名称
docker tag nginx:1.14.2 registry:5000/nginx:1.14.2

# 上传镜像仓库
docker push registry:5000/nginx:1.14.2

创建 nginx-deploy.yaml 文件:

vi nginx-deploy.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:
      nodeSelector:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - nginx
            topologyKey: "kubernetes.io/hostname"
      containers:
      - name: nginx
        image: registry:5000/nginx:1.14.2
        ports:
        - containerPort: 80

创建 nginx 容器:

kubectl apply -f nginx-deploy.yaml

检查创建的 nginx 容器及容器 IP 地址:

kubectl get pods -o wide

随机选择一个容器 IP 地址,用以下命令检查是否连通:

curl http://192.168.217.3/ -I

如果正确返回 HTTP 请求,说明 Kubernetes 集群及容器网络当前工作正常。

results matching ""

    No results matching ""