01Kubernetes-基础入门

什么是Kubernetes

https://kubernetes.io/zh/docs/concepts/overview/what-is-kubernetes/

# k8s前身
borg     

# k8s竞争对手
swarm
mssos

声明式管理(愿望清单式)

Kubernetes参考网站

官网:TP

官方文档:TP

官方介绍:TP

kubeadm官方文档:TP

docker官方文档:TP

prometheus官方文档:TP

ansible安装k8s项目:TP

阿里云ACK:TP

Kubernetes组件介绍

Master:控制平面组件(Control Plane Components)

file

# apiserver
司令部,K8S的唯一入口,所有k8s操作指令,apiserver来接收,接口

# scheduler
资源计算/任务调度

# controller
Pod控制器/创建pod

# etcd
数据库,存储所有组件相应数据

node节点

file

## Node:
# kubelet
客户端,接收创建任务

#kube-proxy
提供网络服务,负载均衡

容器运行时:docker等启动容器的应用
POD:K8S的最小单位,POD主要提供一个根容器,来给其它启动的容器提供资源

Kubernetes架构

单机节点

file

高可用架构

file

Kubernetes核心资源

POD

1.什么是Pod

1.Pod是K8S的最小单位
2.Pod的IP地址是随机的,删除Pod会改变IP
3.Pod都有一个根容器
4.一个Pod内可以由一个容器或多个容器组成
5.一个Pod内的容器共享根容器的网络、名称空间、和文件系统卷
6.一个Pod内的网络地址由根容器提供

Pod创建流程

file

file

POD运行状态

状态 描述
Pending(等待) Pod已经被K8S系统接受,但是有一个或多个容器,尚未创建,亦未运行。此阶段包括等待Pod被调度的时间和通过网络下载镜像的时间
Running(运行) Pod已经绑定到某个节点(node),Pod中所有容器都已被创建,至少有一个容器仍在运行,或者处于启动或重启状态
Succeeded(成功) Pod中所有容器都已成功终止,并且不会再重启
Failed(失败) Pod中所有容器都已成功终止,并且有一个容器是因为失败而终止
Unknown(未知) 因为某些原因无法获取Pod状态,这种情况,通常是因为与Pod所在主机通信失败

Services

提供三种网络图

Service也是K8S核心资源之一,Service定义了服务的入口地址,用来将后端的Pod服务暴露给外部的用户访问。

Node IP
物理节点的ip。
Cluster IP
在pod之上封装了一层ip。
POD IP
每个pod的ip地址,可变的。

file

Label

Label标签是K8S中非常重要的一个属性,Label标签就像身份证一样,可以用来识别K8S的对象。
传统架构中,不同的服务应用之间通讯,都是通过IP和端口,但是在K8S中很多匹配关系都是通过标签来找。

Namespace

Namespace(名称空间)是K8S中非常重要的一个概念,Namespace将集群内部的资源进行隔离划分。
在Namespace中,形成逻辑上的不同项目组或用户组。

Controller

Controller用来管理Pod。
Pod控制器的种类有很多:

  • RC Replication Controller 控制Pod有多个副本
  • RS ReplicaSet RC控制器的升级版
  • Deployment 推荐使用,功能强大,包含了RS控制器
  • DaemonSet 保证所有的Node节点上,有且只有一个Pod运行
  • StatefulSet 有状态的应用,为Pod提供唯一标识,它可以保证部署和scale的顺序

Pod RC和Controller关系

file

Kubernetes实战部署

安装方式

K8S的方式有一堆:

二进制安装
kubeadm
Ansible二进制安装
第三方安装工具 Rancher
云服务的K8S安装 阿里云ACK
。。。。。

二进制安装架构图(拓展)

file

部署环境准备

主机名 IP 角色 配置推荐 安装软件
db01 10.0.0.51 master 1C4G40G API Server、Controller、Scheduler、Kube-proxy、Kubelet、etcd、Kubectl、Kubeadm
db02 10.0.0.52 node1 1C2G40G Docker、Kubelet、Kube-proxy
db03 10.0.0.53 node2 1C2G40G Docker、Kubelet、Kube-proxy

IP规划

三种Service IP
Pod IP 10.2.0.0
Cluster IP 10.1.0.0
Node IP 10.0.0.0

Kubernetes部署

服务器配置至少是2G2核的。如果不是则可以在集群初始化后面增加 --ignore-preflight-errors=NumCPU

1.克隆三台主机

192.168.15.51   k8s-m-01 m1
192.168.15.52   k8s-n-01 n1
192.168.15.53   k8s-n-02 n2

2.修改主机名称

[root@haoda-100 ~]# hostnamectl set-hostname k8s-m-01
[root@haoda-100 ~]# hostnamectl set-hostname k8s-n-01
[root@haoda-100 ~]# hostnamectl set-hostname k8s-n-02

3.系统优化(所有机器全做)

# 关闭selinux

# 关闭防火墙
systemctl disable --now firewalld

# 关闭swap分区
swapoff -a

修改/etc/fstab
echo 'KUBELET_EXTRA_ARGS="--fail-swap-on=false"' > /etc/sysconfig/kubelet   # kubelet忽略swap

# 修改hosts文件
[root@k8s-m-01 ~]# cat /etc/hosts
10.0.0.71   k8s-m01
10.0.0.72   k8s-node01
10.0.0.73   k8s-node02 

# 做免密登录
[root@k8s-m-01 ~]# ssh-keygen -t rsa
[root@k8s-m-01 ~]# for i in m1 n1 n2;do  ssh-copy-id -i ~/.ssh/id_rsa.pub root@$i; done

# 同步集群时间

# 配置镜像源
[root@k8s-m-01 ~]# curl  -o /etc/yum.repos.d/CentOS-Base.repo https://repo.huaweicloud.com/repository/conf/CentOS-7-reg.repo
[root@k8s-m-01 ~]# yum clean all
[root@k8s-m-01 ~]# yum makecache

# 更新系统
[root@k8s-m-01 ~]# yum update -y --exclud=kernel*

# 安装基础常用软件
[root@k8s-m-01 ~]# yum install wget expect vim net-tools ntp bash-completion ipvsadm ipset jq iptables conntrack sysstat libseccomp -y

# 更新系统内核(docker 对系统内核要求比较高,最好使用4.4+)
    [root@k8s-m-01 ~]# wget https://elrepo.org/linux/kernel/el7/x86_64/RPMS/kernel-lt-5.4.107-1.el7.elrepo.x86_64.rpm
    [root@k8s-m-01 ~]# https://elrepo.org/linux/kernel/el7/x86_64/RPMS/kernel-lt-devel-5.4.107-1.el7.elrepo.x86_64.rpm
    ## 安装系统内容
    [root@k8s-m-01 ~]# yum localinstall -y kernel-lt*
    ## 调到默认启动
    [root@k8s-m-01 ~]# grub2-set-default  0 && grub2-mkconfig -o /etc/grub2.cfg
    ## 查看当前默认启动的内核
    [root@k8s-m-01 ~]# grubby --default-kernel
    ## 重启
    [root@k8s-m-01 ~]# reboot

## centos7.9自带
# 安装IPVS
    yum install -y conntrack-tools ipvsadm ipset conntrack libseccomp

    ## 加载IPVS模块
    cat > /etc/sysconfig/modules/ipvs.modules <<EOF
    #!/bin/bash
    ipvs_modules="ip_vs ip_vs_lc ip_vs_wlc ip_vs_rr ip_vs_wrr ip_vs_lblc ip_vs_lblcr ip_vs_dh ip_vs_sh ip_vs_fo ip_vs_nq ip_vs_sed ip_vs_ftp nf_conntrack"
    for kernel_module in \${ipvs_modules}; do
      /sbin/modinfo -F filename \${kernel_module} > /dev/null 2>&1
      if [ $? -eq 0 ]; then
        /sbin/modprobe \${kernel_module}
      fi
    done
EOF

    chmod 755 /etc/sysconfig/modules/ipvs.modules && bash /etc/sysconfig/modules/ipvs.modules && lsmod | grep ip_vs
 # 这条命令必须要有输出结果,如果没有那么你的ipvs就是有问题

# 修改内核启动参数
cat > /etc/sysctl.d/k8s.conf << EOF
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-iptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
fs.may_detach_mounts = 1
vm.overcommit_memory=1
vm.panic_on_oom=0
fs.inotify.max_user_watches=89100
fs.file-max=52706963
fs.nr_open=52706963
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp.keepaliv.probes = 3
net.ipv4.tcp_keepalive_intvl = 15
net.ipv4.tcp.max_tw_buckets = 36000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp.max_orphans = 327680
net.ipv4.tcp_orphan_retries = 3
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.ip_conntrack_max = 65536
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.top_timestamps = 0
net.core.somaxconn = 16384
EOF

# 立即生效
sysctl --system

4.安装docker

# 卸载之前安装过得docker
[root@k8s-m-01 ~]# sudo yum remove docker docker-common docker-selinux docker-engine

# 安装docker需要的依赖包
[root@k8s-m-01 ~]# sudo yum install -y yum-utils device-mapper-persistent-data lvm2

# 安装dockeryum源
[root@k8s-m-01 ~]# wget -O /etc/yum.repos.d/docker-ce.repo https://repo.huaweicloud.com/docker-ce/linux/centos/docker-ce.repo

# 安装docker
[root@k8s-m-01 ~]# yum install docker-ce -y  

# 设置开机自启动
[root@k8s-m-01 ~]# systemctl enable --now docker.service

5.安装kubelet(所有机器都要装)

# 安装kebenetes yum 源
[root@k8s-m-01 ~]# cat <<EOF > /etc/yum.repos.d/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
EOF

# 安装kubelet
[root@k8s-m-01 ~]# yum install -y kubelet-1.21.3 kubeadm-1.21.3 kubectl-1.21.3 
[root@k8s-m-01 ~]# systemctl enable --now kubelet

6、初始化master节点(仅在master节点上执行)

[root@k8s-m-01 ~]# kubeadm init \
--image-repository=registry.cn-hangzhou.aliyuncs.com/k8sos \
--kubernetes-version=v1.21.3 \
--service-cidr=10.96.0.0/12 \
--pod-network-cidr=10.244.0.0/16

7、初始化后续(仅在master节点上执行)

# 建立用户集群权限
[root@k8s-m-01 ~]# mkdir -p $HOME/.kube
[root@k8s-m-01 ~]# sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
[root@k8s-m-01 ~]# sudo chown $(id -u):$(id -g) $HOME/.kube/config

    # 如果是root用户,则可以使用:export KUBECONFIG=/etc/kubernetes/admin.conf

# 安装集群网络插件(flannel.yaml见附件)
[root@k8s-m-01 ~]# kubectl apply -f flannel.yaml

# 将工作节点加入集群
[root@k8s-m-01 ~]# kubeadm token create    --print-join-command 
kubeadm join 192.168.15.31:6443 --token s6svmh.lw88lchyl6m24tts     --discovery-token-ca-cert-hash sha256:4d7e3e37e73176a97322e26fe501d2c27830a7bf3550df56f3a55b68395b507b 
## 注:将上方生成的token复制到node节点上执行。

[root@k8s-m-01 ~]# kubectl get nodes
NAME       STATUS   ROLES                  AGE   VERSION
k8s-m-01   Ready    control-plane,master   13m   v1.20.5
k8s-n-01   Ready    <none>                 35s   v1.20.5
k8s-n-02   Ready    <none>                 39s   v1.20.5

# 检查集群状态
## 第一种方式
[root@k8s-m-01 ~]# kubectl get nodes
NAME       STATUS   ROLES                  AGE     VERSION
k8s-m-01   Ready    control-plane,master   5m56s   v1.20.5

# 第二种方式
[root@k8s-m-01 ~]# kubectl get pods -n kube-system
NAME                               READY   STATUS    RESTARTS   AGE
coredns-f68b4c98f-5t7wm            1/1     Running   0          5m54s
coredns-f68b4c98f-5xqjs            1/1     Running   0          5m54s
etcd-k8s-m-01                      1/1     Running   0          6m3s
kube-apiserver-k8s-m-01            1/1     Running   0          6m3s
kube-controller-manager-k8s-m-01   1/1     Running   0          6m3s
kube-flannel-ds-7bcwl              1/1     Running   0          104s
kube-proxy-ntpjx                   1/1     Running   0          5m54s
kube-scheduler-k8s-m-01            1/1     Running   0          6m3s

# 第三种方式:直接验证集群DNS
[root@k8s-m-01 ~]# kubectl run test -it --rm --image=busybox:1.28.3
If you don't see a command prompt, try pressing enter.
/ # nslookup kubernetes
Server:    10.96.0.10
Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local

Name:      kubernetes
Address 1: 10.96.0.1 kubernetes.default.svc.cluster.local

附件:

---
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: registry.cn-hangzhou.aliyuncs.com/alvinos/flanned:v0.13.1-rc1
        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: registry.cn-hangzhou.aliyuncs.com/alvinos/flanned:v0.13.1-rc1
        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

k8s命令补全黑科技

yum install -y bash-completion
[root@db01 ~]# source /usr/share/bash-completion/bash_completion 
[root@db01 ~]# source <(kubectl completion bash)
[root@db01 ~]# kubectl completion bash > /etc/bash-completion.d/kubectl

山林不向四季起誓 荣枯随缘