zoukankan      html  css  js  c++  java
  • kubernetes

    kubernetes安装master主节点

    kubernetes与docker安装

    修改主机名为master
    关闭swap
    修改hosts文件使用主机名访问node节点
    yum仓库方法快速部署k8s和docker
    master镜像下载配置
    修改iptables文件
    查看kubernetes版本号
    初始化kubeadm下载镜像
    master关闭防火墙
    查看docker镜像
    分发yum仓库源给node节点

    修改主机名为master

    ---
    
    #(2)永久修改主机名
    echo 'master.localdomain' > /etc/hostname
    
    ---
    
    # (1)临时修改主机名, 重启失效
    hostname master
    
    
    
    ---
    

    回去

    关闭swap

    ---
    
    #(1)临时关闭swap分区, 重启失效;
       swapoff  -a
    
    #(2)永久关闭swap分区
     sed -ri 's/.*swap.*/#&/' /etc/fstab  
    
    # (3)kubernetes忽略swap分区,swap为no的情况下让不让他出错,=fales(不让),双重否定在初始化init时添加选项--ignore-preflight-errors=all或swap
    
    cat <<EOF > /etc/sysconfig/kubelet
    KUBELET_EXTRA_ARGS="--fail-swap-on=false"
    EOF
    
    ---
    

    回去

    修改hosts文件使用主机名访问node节点

    ---
    
    cat <<EOF >> /etc/hosts
    192.168.0.3   master
    192.168.0.4   node01
    192.168.0.5   node02
    EOF
    
    ---
    
    ping node01
    ping node02
    
    # 获取ip:ip addr show |awk -F "[ /]+" '$0~/inet/ && $0~/brd/ {print $3}' | head -1
    
    ---
    

    回去

    yum仓库方法快速部署k8s和docker

    ---
    
    # kubernetes,yum地址
    # kubernetes 阿里云镜像地址:https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
    # kubernetes 阿里云镜像验证密钥地址:https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg 
    https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
    
    ---
    
    # docker,yum地址
    # docker 阿里云repo文件地址: https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    
    
    # step 1: 安装必要的一些系统工具
    sudo yum install -y yum-utils device-mapper-persistent-data lvm2
    
    # Step 2: 添加软件源信息
    sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    
    # Step 3: 更新并安装Docker-CE
    sudo yum makecache fast
    
    sudo yum -y install docker-ce
    
    # Step 4: 开启Docker服务
    systemctl enable docker && systemctl start docker
    
    ---
    
    ################### kubernetes
    
    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=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
    
    ---
    
    # yum仓库说明:
    
    # 文件名repo后缀
    # [仓库名独一无二]
    # name=描述
    # baseurl=镜像地址
    # gpgcheck=1开启验证,0关闭验证
    # gpgkey=验证密钥地址
    # enable=1启用源,0不启用源
    
    ---
    
    # 验证仓库:yum repolist
    
    ---
    

    回去

    master镜像下载配置

    ---
    
    ###:方法一,经验证方法一不可用,以后在修
    # 使用代理
    echo 'Environment="HTTPS_PROXY=https://qijo5n63.mirror.aliyuncs.com"' >> /usr/lib/systemd/system/docker.service
    # 豁免代理的地址
    echo 'Environment="NO_PROXY=127.0.0.0/8,172.0.0.1/16"' >> /usr/lib/systemd/system/docker.service
    # vi /usr/lib/systemd/system/docker.service 编辑文件配置信息添加到[Service]项
    # 警告:docker.service在磁盘上已更改。 运行“ systemctl daemon-reload”以重新加载单元。
    systemctl daemon-reload
    systemctl restart docker
    docker info
    
    ---
    
    ###:方法二
    # 无效待定
    touch /etc/docker/daemon.json
    cat << EOF > /etc/docker/daemon.json
    {
      "registry-mirrors": [
        "https://dockerhub.azk8s.cn"
      ],
    }
    EOF
    systemctl restart docker
    docker info
    
    ---
    
    ### 或
    
    ---
    
    touch /etc/docker/daemon.json
    cat <<EOF > /etc/docker/daemon.json
    {
      "registry-mirrors": [
        "https://dockerhub.azk8s.cn"
      ],
      "exec-opts": ["native.cgroupdriver=systemd"],
      "log-driver": "json-file",
      "log-opts": {
        "max-size": "100m"
      },
      "storage-driver": "overlay2",
      "storage-opts": [
        "overlay2.override_kernel_check=true"
      ],
      "dns":["114.114.114.114"]
    }
    EOF
    systemctl restart docker
    docker info
    
    
    ---
    
    
    ### 或
    
    ---
    
    cat << EOF > /etc/docker/daemon.json
    {
      "registry-mirrors": [
        "https://dockerhub.azk8s.cn",
        "https://docker.mirrors.ustc.edu.cn",
        "https://registry.docker-cn.com",
        "https://dl6ejneo.mirror.aliyuncs.com"
      ],
      "data-root": "/docker",
      "exec-opts": ["native.cgroupdriver=systemd"],
      "log-driver": "json-file",
      "log-opts": {
        "max-size": "100m"
      },
      "storage-driver": "overlay2",
      "storage-opts": [
        "overlay2.override_kernel_check=true"
      ],
      "dns":["114.114.114.114"]
    }
    EOF
    systemctl restart docker
    docker info
    
    
    
    ---
    
    # docker.service的作业失败,因为尝试启动服务的次数太多。 有关详细信息,请参见“ systemctl状态docker.service”和“ journalctl  -xe”。
    # 要强制启动,请再次使用“ systemctl重置失败的docker.service”,然后再次使用“ systemctl启动docker.service”。
    systemctl reset-failed docker.service
    systemctl start docker.service
    
    
    ---
    

    回去

    修改iptables文件

    ---
    
    echo "1" >> /proc/sys/net/bridge/bridge-nf-call-ip6tables
    echo "1" >> /proc/sys/net/bridge/bridge-nf-call-iptables
    
    ---
    
    echo "1" >> /proc/sys/net/ipv4/ip_forward
    
    ---
    

    回去

    查看kubernetes版本号

    ---
    
    kubelet --version
    
    ---
    

    回去

    初始化kubeadm下载镜像

    ---
    
    #!/bin/bash
    
    # 查看当前kubernetes版本所需要的镜像
    # kubeadm config images list
    
    # 使用阿里云拉镜像:
    
    ip=$(ip addr | grep 'eth0' | grep inet | awk -F " " '{print $2}' | awk -F '/' '{print $1}')
    
    echo 'master.localdomain' > /etc/hostname
    
    hostnamectl set-hostname master
    
    # 修改主机名立即生效
    
    # hostnamectl set-hostname node01
    
    # hostnamectl set-hostname node02
    
    swapoff  -a
    
    # sed -ri 's/.*swap.*/#&/' /etc/fstab  
    
    cat <<EOF >> /etc/hosts
    192.168.0.3   master
    192.168.0.4   node01
    192.168.0.5   node02
    EOF
    
    sudo yum install -y yum-utils device-mapper-persistent-data lvm2
    
    sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    
    sudo yum makecache fast
    
    sudo yum -y install docker-ce
    
    systemctl enable docker && systemctl restart docker
    
    cat <<EOF > /etc/docker/daemon.json
    {
      "registry-mirrors": [
        "https://qijo5n63.mirror.aliyuncs.com"
      ],
      "exec-opts": ["native.cgroupdriver=systemd"],
      "log-driver": "json-file",
      "log-opts": {
        "max-size": "100m"
      },
      "storage-driver": "overlay2",
      "storage-opts": [
        "overlay2.override_kernel_check=true"
      ],
      "dns":["114.114.114.114"]
    }
    EOF
    
    systemctl restart docker
    
    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=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
    
    yum install -y kubelet kubeadm kubectl
    
    systemctl enable kubelet && systemctl start kubelet
    
    echo "1" >> /proc/sys/net/bridge/bridge-nf-call-ip6tables
    
    echo "1" >> /proc/sys/net/bridge/bridge-nf-call-iptables
    
    echo "1" >> /proc/sys/net/ipv4/ip_forward
    
    setenforce 0
    systemctl stop firewalld 
    
    ---
    
    
    ### dockerhub良心公开仓库 aiotceo 更新最新k8s镜像
    # aiotceo/kube-proxy:v1.18.1
    # aiotceo/kube-apiserver:v1.18.1
    # aiotceo/kube-controller-manager:v1.18.1
    # aiotceo/kube-scheduler:v1.18.1
    
    ### 镜像更新
    # sudo docker tag 0d40868643c6 registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/kube-proxy:v1.18.2
    # sudo docker tag ace0a8c17ba9 registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/kube-controller-manager:v1.18.2
    # sudo docker tag a3099161e137 registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/kube-scheduler:v1.18.2
    # sudo docker tag 6ed75ad404bd registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/kube-apiserver:v1.18.2
    
    # sudo docker push registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/kube-proxy:v1.18.2
    # sudo docker push registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/kube-controller-manager:v1.18.2
    # sudo docker push registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/kube-scheduler:v1.18.2
    # sudo docker push registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/kube-apiserver:v1.18.2
    
    KUBE_VERSION=`kubelet --version |  awk -F ' ' '{print $2}'`
    list=$(kubeadm config images list --kubernetes-version=${KUBE_VERSION})
    
    
    sudo docker pull registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/quay.io_coreos_flannel:v0.11.0-amd64
    
    sudo docker tag registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/quay.io_coreos_flannel:v0.11.0-amd64 quay.io/coreos/flannel:v0.11.0-amd64
    
    sudo docker rmi registry.cn-hangzhou.aliyuncs.com/k8s_containers_google/quay.io_coreos_flannel:v0.11.0-amd64
    
    for line in ${list}
    do
      echo ${line}
    #    docker pull  $line
    image=`echo ${line} | awk '{ sub(/k8s.gcr.io/,"registry.cn-hangzhou.aliyuncs.com/k8s_containers_google"); print $0 }'`
    echo ${image}
    docker pull ${image}
    docker tag   ${image} ${line}
    docker rmi ${image}
    
    done
    
    
    
    # 主节点init初始化
    kubeadm init 
    --kubernetes-version=${KUBE_VERSION} 
    --pod-network-cidr=10.244.0.0/16 
    --apiserver-advertise-address=${ip} 
    --service-cidr=10.96.0.0/12
    #--token-ttl 0 
    
    #--ignore-preflight-errors=all
    #--apiserver-cert-extra-sans=${ip} 
    #--apiserver-advertise-address=192.168.0.120
    mkdir -p $HOME/.kube
    cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
    chown $(id -u):$(id -g) $HOME/.kube/config
    
    
    
    # --kubernetes-version  为控制平面选择特定的Kubernetes版本。 (默认为“稳定-1”)
    # --pod-network-cidr  指定Pod网络的IP地址范围。 如果设置,控制平面将自动为每个节点分配CIDR。
    # --token-ttl  自动删除令牌之前的持续时间(例如1s,2m,3h)。 如果设置为“ 0”,则令牌将永不过期(默认为24h0m0s)
    # --apiserver-advertise-address  API服务器将通告其正在侦听的IP地址。 如果未设置,将使用默认网络接口。
    # --apiserver-cert-extra-sans 用于API服务器服务证书的可选额外主题备用名称(SAN)。 可以是IP地址和DNS名称。
    # --ignore-preflight-errors 一系列检查的列表,其错误将显示为警告。 例如:“ IsPrivilegedUser,Swap”。 值“ all”忽略所有检查的错误。
    # --service-cidr  为service VIPs使用不同的IP地址。(默认“10.96.0.0/12”)
    
    ### flannel 网络模型初始化方式
    # kubeadm init  --kubernetes-version=v1.17.4 --pod-network-cidr=10.244.0.0/16 --service-cidr=10.96.0.0/12 --apiserver-cert-extra-sans=
    
    ### 添加临时ip
    # ip address add 10.96.0.2/16 dev enp0s8
    
    ### 删除临时ip
    # ip -f inet addr delete 10.0.64.102/32  dev enp0s8
    
    ### Calico 网络模型
    # kubectl apply -f https://docs.projectcalico.org/v3.11/manifests/calico.yaml
    
    
    
    ### flannel 网络模型
    kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/2140ac876ef134e0ed5af15c65e414cf26827915/Documentation/kube-flannel.yml
    
    cat << EOF > /root/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']
      defaultAddCapabilities: []
      requiredDropCapabilities: []
      # Host namespaces
      hostPID: false
      hostIPC: false
      hostNetwork: true
      hostPorts:
      - min: 0
        max: 65535
      # SELinux
      seLinux:
        # SELinux is unsed in CaaSP
        rule: 'RunAsAny'
    ---
    kind: ClusterRole
    apiVersion: rbac.authorization.k8s.io/v1beta1
    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/v1beta1
    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: |
        {
          "cniVersion": "0.2.0",
          "name": "cbr0",
          "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-amd64
      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: beta.kubernetes.io/os
                        operator: In
                        values:
                          - linux
                      - key: beta.kubernetes.io/arch
                        operator: In
                        values:
                          - amd64
          hostNetwork: true
          tolerations:
          - operator: Exists
            effect: NoSchedule
          serviceAccountName: flannel
          initContainers:
          - name: install-cni
            image: quay.io/coreos/flannel:v0.11.0-amd64
            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.11.0-amd64
            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"]
            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
    ---
    apiVersion: apps/v1
    kind: DaemonSet
    metadata:
      name: kube-flannel-ds-arm64
      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: beta.kubernetes.io/os
                        operator: In
                        values:
                          - linux
                      - key: beta.kubernetes.io/arch
                        operator: In
                        values:
                          - arm64
          hostNetwork: true
          tolerations:
          - operator: Exists
            effect: NoSchedule
          serviceAccountName: flannel
          initContainers:
          - name: install-cni
            image: quay.io/coreos/flannel:v0.11.0-arm64
            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.11.0-arm64
            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"]
            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
    ---
    apiVersion: apps/v1
    kind: DaemonSet
    metadata:
      name: kube-flannel-ds-arm
      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: beta.kubernetes.io/os
                        operator: In
                        values:
                          - linux
                      - key: beta.kubernetes.io/arch
                        operator: In
                        values:
                          - arm
          hostNetwork: true
          tolerations:
          - operator: Exists
            effect: NoSchedule
          serviceAccountName: flannel
          initContainers:
          - name: install-cni
            image: quay.io/coreos/flannel:v0.11.0-arm
            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.11.0-arm
            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"]
            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
    ---
    apiVersion: apps/v1
    kind: DaemonSet
    metadata:
      name: kube-flannel-ds-ppc64le
      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: beta.kubernetes.io/os
                        operator: In
                        values:
                          - linux
                      - key: beta.kubernetes.io/arch
                        operator: In
                        values:
                          - ppc64le
          hostNetwork: true
          tolerations:
          - operator: Exists
            effect: NoSchedule
          serviceAccountName: flannel
          initContainers:
          - name: install-cni
            image: quay.io/coreos/flannel:v0.11.0-ppc64le
            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.11.0-ppc64le
            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"]
            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
    ---
    apiVersion: apps/v1
    kind: DaemonSet
    metadata:
      name: kube-flannel-ds-s390x
      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: beta.kubernetes.io/os
                        operator: In
                        values:
                          - linux
                      - key: beta.kubernetes.io/arch
                        operator: In
                        values:
                          - s390x
          hostNetwork: true
          tolerations:
          - operator: Exists
            effect: NoSchedule
          serviceAccountName: flannel
          initContainers:
          - name: install-cni
            image: quay.io/coreos/flannel:v0.11.0-s390x
            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.11.0-s390x
            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"]
            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
    EOF
    
    kubectl apply -f kube-flannel.yml
    
    ---
    

    回去

    master关闭防火墙

    ---
    # 重启后hostname,swap生效后关闭防火墙
    setenforce 0
    systemctl stop firewalld
    
    ---
    

    回去

    node节点加入集群

    ---
    
    kubeadm join 192.168.0.3:6443 --token q5xjqs.08ol2v93nwg1hobb 
        --discovery-token-ca-cert-hash sha256:2f932dec61abace1f052cbbec88e7c58e6516dec4c75856e6c58ad2562b90144 --ignore-preflight-errors=all
    
    ---
    

    回去

    查看docker镜像

    ---
    
    docker image ls
    
    # image 管理镜像
    # ls 列出镜像
    
    ---
    

    回去

    分发yum仓库源给node节点

    ---
    
    scp /etc/yum.repos.d/kubernetes.repo /etc/yum.repos.d/docker-ce.repo node:/etc/yum.repos.d/
    
    ---
    

    回去

    kubernetes安装node01节点

    node01节点配置

    node01关闭防火墙
    修改主机名为node01
    node01关闭swap
    安装kube,docker
    node01镜像下载配置
    node01初始化kubeadm下载镜像

    node01关闭防火墙

    ---
    
    setenforce 0
    systemctl stop firewalld
    
    ---
    

    修改主机名为node01

    ---
    
    echo 'node01.localdomain' > /etc/hostname
    
    ---
    

    回去

    node01关闭swap

    ---
    
    #(1)临时关闭swap分区, 重启失效;
       swapoff  -a
    
    #(2)永久关闭swap分区
     sed -ri 's/.*swap.*/#&/' /etc/fstab  
    
    # (3)kubernetes忽略swap分区,swap为no的情况下让不让他出错,=fales(不让),双重否定在初始化init时添加选项--ignore-preflight-errors=all或swap
    
    cat <<EOF > /etc/sysconfig/kubelet
    KUBELET_EXTRA_ARGS="--fail-swap-on=false"
    EOF
    
    ---
    

    回去

    node01修改hosts文件使用主机名访问node节点

    ---
    
    cat <<EOF >> /etc/hosts
    192.168.0.3   master
    192.168.0.4   node01
    192.168.0.5   node02
    EOF
    
    ---
    
    ping master
    ping node02
    
    # 获取ip:ip addr show |awk -F "[ /]+" '$0~/inet/ && $0~/brd/ {print $3}' | head -1
    
    ---
    

    回去

    安装kube,docker

    ---# kubernetes
    
    
    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=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
    
    ---# docker
    
    # step 1: 安装必要的一些系统工具
    sudo yum install -y yum-utils device-mapper-persistent-data lvm2
    # Step 2: 添加软件源信息
    sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    # Step 3: 更新并安装Docker-CE
    sudo yum makecache fast
    sudo yum -y install docker-ce
    # Step 4: 开启Docker服务
    systemctl enable docker && systemctl start docker
    
    ---# yum仓库说明:
    
    # 文件名repo后缀
    # [仓库名独一无二]
    # name=描述
    # baseurl=镜像地址
    # gpgcheck=1开启验证,0关闭验证
    # gpgkey=验证密钥地址
    # enable=1启用源,0不启用源
    
    

    回去

    node01镜像下载配置

    
    ---
    
    touch /etc/docker/daemon.json
    cat <<EOF > /etc/docker/daemon.json
    {
      "registry-mirrors": [
        "https://dockerhub.azk8s.cn"
      ],
      "exec-opts": ["native.cgroupdriver=systemd"],
      "log-driver": "json-file",
      "log-opts": {
        "max-size": "100m"
      },
      "storage-driver": "overlay2",
      "storage-opts": [
        "overlay2.override_kernel_check=true"
      ],
      "dns":["114.114.114.114"]
    }
    EOF
    systemctl restart docker
    docker info
    
    ---
    
    
    # docker.service的作业失败,因为尝试启动服务的次数太多。 有关详细信息,请参见“ systemctl状态docker.service”和“ journalctl  -xe”。
    # 要强制启动,请再次使用“ systemctl重置失败的docker.service”,然后再次使用“ systemctl启动docker.service”。
    systemctl reset-failed docker.service
    systemctl start docker.service
    
    ---
    

    回去

    node01初始化kubeadm下载镜像

    ---
    
    #!/bin/sh
    KUBE_VERSION=`kubelet --version |  awk -F ' ' '{print $2}'`
    list=$(kubeadm config images list --kubernetes-version=${KUBE_VERSION})
    for line in ${list}
    do
      echo ${line}
    #    docker pull  $line
    image=`echo ${line} | awk '{ sub(/k8s.gcr.io/,"gcr.azk8s.cn/google_containers"); print $0 }'`
    echo ${image}
    docker pull ${image}
    docker tag   ${image} ${line}
    docker rmi ${image}
    done
    
    ---
    

    回去

    kubeadm reset(还原kubectl init修改)

    ---
    
    kubeadm reset
    # reset 尽最大努力还原通过“ kubeadm init”或“ kubeadm join”对此主机所做的更改
    
    ---
    
    
    ---
    

    应用基础操作

    显示集群信息
    显示组件状态信息
    查看API群组
    从yaml来加载部署镜像容器
    patch向yaml打补丁
    运行部署镜像容器
    查看当前系统上deployment(部署)了的
    查看名称空间
    查看node节点
    查看pod
    操作pod
    查看控制器
    查看服务
    操作服务
    查看滚动历史
    标签选择器
    edit修改资源清单
    暴露端口
    进入容器执行命令
    获取日志

    显示集群信息

    ---
    kubectl cluster-info
    
    ---
    
    Kubernetes master is running at https://10.192.46.240:6443
    KubeDNS is running at https://10.192.46.240:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
    
    Kubernetes主服务器运行在https://10.192.46.240:6443
    KubeDNS运行在https://10.192.46.240:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
    在外部执行的一个端口代理转发的访问方式
    ---
    

    回去

    显示组件状态信息

    ---
    
    kubectl get cs
    同
    kubectl get componentstatus
    
    
    ---
    
    # NAME                 STATUS    MESSAGE             ERROR
    # scheduler            Healthy   ok                  
    # controller-manager   Healthy   ok                  
    # etcd-0               Healthy   {"health":"true"}   
    
    ---
    
    # NAME(组件名称)
    # STATUS(状态)
    # MESSAGE(信息)
    # ERROR(错误)
    
    ---
    
    # Healthy(健康)
    # ok(健康与否,ok健康)
    # {"health":"true"}(健康”:“ true)
    
    ---
    

    回去

    查看API群组

    ---
    
    kubectl api-versions
    
    # api-versions    以“组/版本”的形式打印服务器上支持的API版本
    # v1(核心群组,pod属于最核心资源,属于v1)
    # apps/v1(应用程序管理的核心资源,控制器,属于应用程序管理的核心资源)
    # apps/v1beta1(beta属于公测版,(公共测试))
    
    ---
    

    回去

    从yaml来加载部署镜像容器

    ---
    
    kubectl apply -f pod-demo.yaml
    
    # 可以不用使用edit,直接修改yaml文件,apply可以多次更新,同步
    # apply    通过文件名或标准输入流(stdin)对资源进行配置(声明式“更新”或“创建”,既可以去创建也可以去更新)
    # -f    指定文件
    
    ---
    
    kubectl create -f pod-demo.yaml
    
    pod/pod-demo created
    
    # 创建时只可以装填一次,创建后不可以再次创建
    # create    从文件或标准输入创建资源。
    # -f    指定文件
    
    ---
    

    回去

    patch向yaml打补丁

    ---
    
    kubectl patch deployment nginx-deployment -p '{"spec":{"replicas":5}}'
    # 给replicas打补丁创建5个pod
    
    ---
    
    kubectl patch deployment nginx-deployment -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":1,"maxUnavailable":0}}}}'
    # "maxSurge":1 能超出所指定副本数的1个,maxUnavailable":0,不允许少于指定副本数的0个
    
    # -p,--patch ='':要应用于资源JSON文件的补丁。kubectl edit deployment nginx-deployment中的数据会更新
    
    ---
    

    回去

    运行部署镜像容器

    ---
    
    kubectl run nginx-deploy --image=nginx:1.14-alpine  --port=80 --replicas=1 --dry-run=true -- /bin/sh
    
    # nginx-deploy    取名
    
    # --image=nginx:1.14-alpine    使用镜像(此镜像可以是本地docker镜像也可以是hub仓库镜像路径)
    
    # --port=80    暴露哪个端口,默认暴露
    
    # --replicas=1    创建几个pod,一个控制器可以驱动多个pod,因为是无状态的,默认是一个
    
    # --dry-run=true    是否为干跑模式,ture为真
    
    # -- /bin/sh    创建pod后只运行/bin/sh,不在跑nginx这个默认程序
    
    # pod被创建但是还并没有部署(deployment)无法查看到,需要暴露端口
    
    ---
    
    deployment.apps/nginx-deploy created (dry run)
    
    # deployment    这个控制器下
    # apps    控制的应用程序
    # nginx-deploy    叫做nginx-deploy
    # created    创建完成
    # (dry run)    但当前dry干跑模式,并没有执行,如果需要执行需要去掉--dry-run=true选项
    
    
    ---
    

    回去

    查看当前系统上deployment(部署)了的

    ---
    
    kubectl get deployment
    
    ---
    
    如果运行后这没有显示,查看之前运行的结果,pod的STATUS(状态),yaml文件创建的看不到
    
    ---
                           
    # NAME          READY(准备)   UP-TO-DATE   AVAILABLE(可用的)           AGE
    # nginx           1/1            1           1(是否就绪)                136m
    
    # UP-TO-DATE    更新状态1为最新
    
    # AVAILABLE    可用的是0个
    
    # AGE    启动时间
    
    ---
    

    回去

    查看名称空间

    ---
    
    kubectl get ns
    
    ---
    
    NAME(名称空间名称)    STATUS(状态)            AGE(启动时间)
                           Active(活性(活动))     64m(64分钟)
    
    # 系统级的pod都在kube-system名称空间中
    ---
    

    回去

    查看node节点

    ---
    
    ### 获取集群node节点信息
    
    kubectl get nodes
    
    ---
    
    NAME(节点名称)    STATUS(状态)                        ROLES(角色)    AGE(启动时间)    VERSION(版本信息)
                       NotReady(没有准备好(未就绪状态))     master(主)    13m(13分钟)      v1.17.4
    
    ---
    
    ### 获取单个node节点详细信息
    
    kubectl describe  node  node01
    
    describe       显示一个指定 resource(资源) 或者 group(组) 的 resources(资源) 详情
    ---
    

    回去

    查看pod

    ---
    
    ### 获取正在运行的pod(默认是default名称空间)
    
    
    kubectl get pods -o wide -w
    
    NAME                           READY   STATUS    RESTARTS   AGE    IP              NODE                 NOMINATED NODE   READINESS GATES
    nginxhaoran-7899554569-96sh2   1/1     Running   0          149m   192.168.98.65   node01.localdomain   <none>           <none>
    
    # -o wide 显示详细信息
    # pod 以ps输出格式列出所有Pod。
    #  -w, --watch=false:列出/获取请求的对象后,请注意更改。 如果未提供对象名称,则排除未初始化的对象。
    
    
    ---
    
    # IP    pod的ip地址,pod运行的节点上有相同网络的网桥,这个node节点下创建的pod都在个网络下
    # NODE    pod运行在哪个node节点上
    
    ---
    
    STATUS    
    
    Running    运行
    Terminating    终止
    Pending    待定(挂起,条件不能满足,调度没有完成,比如已经创建但是没有适合他运行的节点)
    Failed    失败
    Succeeded    成功
    Unknown    未知状态(一个pod处于什么状态,是API Server跟运行这个pod的节点无法网络通信)
       
    ---
    
    ### 获取指定(名称空间)中运行的所有pod
    
    kubectl get pod -n kube-system -o wide
    
    # -n 指定名称空间
    # -o wide 以ps输出格式列出所有pod,并提供更多信息(例如节点名称)。
    
    ---
    
    # 核心组件pod信息
    # coredns    coredns插件需要网络插件的支持,可以安装calico或者flannel就可以,因为kuberntes中的所有pod都是基于service域名解析后,再负载均衡分发到service后端的各个pod服务中,那么如果没有DNS解析,则无法查到各个服务对应的service服务,容器内由于没有kubernetes的DNS服务解析,容器是找不到service的IP地址,那么也就找不到后面的服务了,所以CoreDNS的解析服务是必须要安装好的。
    
    ---
    
    ### 获取所有(名称空间)中运行的所有pod
    
    kubectl get pod --all-namespaces
    或
    kubectl get pod -A
    
    # -A,--all-namespaces = false:如果存在,则在所有命名空间中列出请求的对象,即使使用--namespace指定,当前上下文中的命名空间也将被忽略。
    # -o wide 以ps输出格式列出所有pod,并提供更多信息(例如节点名称)。
    
    
    ---
    
    ### 输出pod的详细信息,输出为yaml格式
    
    kubectl get pod nginx-deploy  -o yaml
    
    # 默认是default名称空间中的pod
    
    ---
    
    # 有键值对儿组成
    
    # apiVersion(属于k8s哪个api版本,api组就叫群组名称和版本)
    # kind(资源类别,pod和控制器和servie(服务)都是一种资源类别)
    # metadata:(元数据,内部要嵌套其它二级字段或三级字段来定义)
    # spec:(规格,(重要字段,定义我们所期望的特性)将要创建的资源要遵循那种规范,比如容器应该有几个,每一个容器应该使用那种镜像文件来创建,内部要嵌套其它二级字段或三级字段来定义)
    # status:(当前资源的当前的状态,只读有系统定义)
    ---
    
    ### 显示pod的详细信息,比如镜像版本号,pod再哪个节点上
    
    kubectl describe pods nginx-deployment-8d9f7c4f-gvsw9
    
    # 默认是default名称空间中的pod
    
    # Name    pod名
    # Namespace    所在的名称空间
    # Priority    优先级
    # Node    运行在哪个节点上
    # Labels    自己定义的标签
    # Status    当前状态,Running(运行)
    # IP    ip地址
    # Containers    内部容器
    # Events    详细信息
    ## From    从,哪个调度器调度
    ## Message    信息,分配到哪个节点了
    
    ---
    
    kubectl --insecure-skip-tls-verify --context=employee-context get pods
    # 一种选择是告诉kubectl您您不想验证证书。显然,这带来了安全性问题,但我想您只是在测试
    ---
    

    回去

    操作pod

    ---
    
    ### 删除pod
    
    ---
    
    kubectl delete pods nginxhaoran-7899554569-96sh2
    
    # delete 按文件名,stdin,资源和名称或资源和标签选择器删除资源,删除pod后会,如果pod在运行状态,立即重新创建一个
    
    ---
    
    kubectl delete pod nginx-deploy  --force --grace-period=0
    
    # 强制删除卡死的pod
    # --force    如果为true,请立即从API中删除资源并跳过正常删除操作。请注意,立即删除某些资源可能会导致不一致或数据丢失,因此需要确认。
    # grace-period    表示过渡存活期,默认30s,在删除POD之前允许POD慢慢终止其上的容器进程,从而优雅退出,0表示立即终止POD
    
    ----
    
    kubectl delete -f pod-demo.yaml
    
    # 删除已yaml文件创建的pod,没有规则后pod不在重启
    
    
    ---
    

    回去

    查看控制器

    ---
    
    kubectl get rs
    或
    kubectl get ReplicaSet -o wide
    # 查看ReplicaSet 此控制器下的pod
    
    ---
    
    NAME        DESIRED   CURRENT   READY   AGE
    nginx-pod   2         2         0       30s
    
    ---
    
    DESIRED (期望的)
    CURRENT (当前)
    READY (准备(就绪))
    
    ---
    

    回去

    查看服务

    ---
    
    kubectl get svc
    或
    kubectl get rc,services
    或指定名称空间
    kubectl get svc -n kube-system
    
    # 以ps输出格式一起列出所有复制控制器和服务。
    
    ---
    
    NAME                  TYPE(类型             CLUSTER-IP(集群ip)           EXTERNAL-IP   PORT(S)           AGE
    service/kubernetes    ClusterIP(集群ip)     10.96.0.1                     <none>        443/TCP          4h13m
    service/nginx         NodePort (节点端口)   10.108.214.115(动态ip)       <none>        800:30106/TCP    13m
    
    # 800:30106/TCP,30106端口是动态绑定的,每一个node节点ip都可以通过此端口访问到nginx
    
    # api server 有两个地址一个是面向集群内的,一个是面向集群外的,这里是集群内部的地址,集群内的各种pod需要于kubernetes上的api service联系都要通过这个地址联系
    
    ---
    
    ### 显示服务的详细信息
    
    kubectl describe svc nginx
    
    ---
    
    Name:              nginxhaoran
    Namespace:         default
    Labels:            run=nginxhaoran
    Annotations:       <none>
    Selector:          run=nginxhaoran
    Type:              ClusterIP
    IP:                10.108.214.115
    Port:              <unset>  80/TCP
    TargetPort:        80/TCP
    Endpoints:         192.168.98.66:80
    Session Affinity:  None
    Events:            <none>
    
    
    ---
    

    回去

    操作服务

    ---
    
    ### 删除服务
    
    kubectl delete svc redis
    
    ---
    
    ### 扩展pod,通过指定扩展数,来实现扩展和缩减
    
    kubectl scale --replicas=5 deployment nginx
    
    # scale    为Deployment,ReplicaSet或Replication Controller设置新的大小
    # --replicas=0    新的所需副本数。 需要。
    
    ---
    
    ### 更新(升级或回滚)镜像
    kubectl set image deployment/nginx nginx=nginx:1.17.9
    或
    kubectl set image deployment nginx nginx=nginx:1.17.9
    # 镜像名使用kubectl get deployment中显示的
    
    # set            为 objects(对象) 设置一个指定的特征
    #image          更新一个 pod template 的镜像
    
    ---
    
    ### 显示更新过程
    kubectl rollout status deployment nginx
    
    # 使用kubectl describe pods nginx-deployment-8d9f7c4f-gvsw9查看pod使用的镜像版本号
    
    # rollout        管理资源部署
    # status      显示 rollout 的状态
    ---
    
    ### 回滚或回到指定镜像版本,默认是之前
    
    kubectl rollout undo deployment nginxhaoran
    
    # undo        撤销上一次的 rollout
    
    ---
    

    回去

    查看滚动历史

    ---
    
    kubectl rollout history deployment nginx-deployment
    
    # rollout       管理资源部署(滚动历史)
    
    # pause       标记提供的 resource 为中止状态,暂停更新
    # restart     重新启动资源,继续跟新
    
    kubectl rollout history deployment nginx-deployment
    # history     显示 rollout 历史(可以指明看谁的滚动历史)
    # 1         <none>
    # 2         <none>
    
    kubectl rollout undo deployment nginx-deployment --to-revision=1
    # undo        撤销上一次的 rollout (回滚)
    # kubectl rollout history deployment nginx-deployment
    # deployment.apps/nginx-deployment 
    # REVISION  CHANGE-CAUSE
    # 2         <none>
    # 3         <none>
    # 第一步版被还原成第三版 kubectl get rs -o wide,回到了第一个版本
    
    
    ---
    
    REVISION    改变(改版)
    CHANGE-CAUSE    变更原因
    ---
    

    回去

    标签选择器

    ---
    
    ### 给资源打标签
    # 资源可以是nodes或者pod
    
    kubectl label pods pod-demo release=canary
    # pod打标
    kubectl label nodes node01.localdomain disktype=ssd
    # node打标,节点打标的好处是使用资源清单再添加资源时,可以使用nodeSelector字段让资源对节点有倾向性
    
    # 不可重复打标会报错,需要添加选项覆盖标签
    # label         更新在这个资源上的 labels(标签)
    
    ---
    
    kubectl label pods pod-demo release=stable --overwrite
    # node,pod打标过程都一样
    
    # --overwrite = false:如果为true,则允许覆盖标签,否则拒绝覆盖现有标签的标签更新。
    
    ---
    
    ### 标签选择器显示pod标签
    
    kubectl get pods --show-labels
    或
    kubectl get pods -L app,run
    或
    kubectl get pods -l app
    或
    kubectl get pods -l release=canary,app=nginx
    # 等值关系,与关系,必须同时满足条件
    或
    kubectl get pods -l release!=canary
    # 不等值关系
    或
    kubectl get pods -l "release in (canary,beta,alpha)"
    # 集合关系,满足集合中其中一个标签值
    或
    kubectl get pods -l "release notin (canary,beta,alpha)"
    # 取反集合关系,满足不属于集合中其中一个标签值
    
    # 默认是default名称空间中的pod
    
    --show-labels = false:打印时,将所有标签显示为最后一列(默认为隐藏标签列)
    
    -L,--label-columns = []:接受以逗号分隔的标签列表,这些标签将作为列显示。 名称区分大小写。 您还可以使用多个标志选项,例如-L label1 -L label2 ...(线索标签对应的值)
    
    -l,--selector ='':要过滤的选择器(标签查询),支持'=','=='和'!='(例如-l key1 = value1,key2 = value2)
    ---
    
    NAME                           READY   STATUS    RESTARTS   AGE    LABELS
    nginxhaoran-7899554569-4r94b   1/1     Running   0          117m   pod-template-hash=7899554569,run=nginxhaoran
    
    # pod在被删除后重新创建pod名不同但是标签是不变的,
    
    ---
    

    回去

    edit修改资源清单

    ---
    
    kubectl edit rs nginx-pod
    
    # 好处 动态修改模板
    # 可以更新升级,也就是改容器的镜像文件版本号,改了控制器的,但是pod资源并不会修改,只有重建的pod资源他的版本才是新版本的
    # rs 控制器ReplicaSet缩写,(可以使用pod,只是选择资源而已)
    # nginx-pod 控制器模板名
    
    ---
    

    回去

    暴露端口

    ---
    
    kubectl expose deployment  nginxhaoran --port=80 --target-port=80 --protocol=TCP
    service/nginxhaoran exposed
    
    # expose
    # 使用 replication controller, service, deployment 或者 pod 并暴露它作为一个 新的
    
    # nginxhaoran
    # pod名
    
    # --port=80 --target-port=80
    # -port='': 服务的端口应该被指定. 如果没有指定, 从被创建的资源中复制
    # --target-port ='':服务应将流量定向到的容器上端口的名称或端口号
    # 将服务端口暴露给pod端口
    
    # --protocol=TCP
    # --protocol='': 创建 service 的时候伴随着一个网络协议被创建. 默认是 'TCP'
    
    # 以上暴露,集群内pod可以访问
    
    ---
    
    ### 暴露端口(集群外可以访问)
    
    # 编辑名为“ nginx”的服务:
    
    kubectl edit svc nginx
    # edit           在服务器上编辑一个资源
    
    # 将spec字段下的type(类型)ClusterIP --> NodePort,:wq保存退出,通过kubectl get svc查看
    
    ---
    

    回去

    进入容器执行命令

    ---
    
    kubectl exec -it pod-demo -c nginx -- /bin/sh
    # 在那个pod(pod-demo)中的那个容器(nginx)上执行命令
    
    # exec    在一个容器中执行一个命令
    # -i,-stdin = false:将stdin(标准输入)传递到容器
    # -t,--tty = false:Stdin(标准输入)是TTY
    # -c,--container ='':容器名称 如果省略,将选择容器中的第一个容器
    
    ---
    

    回去

    获取日志

    ---
    
    kubectl logs pod-demo nginx
    # logs    输出容器在 pod 中的日志
    
    ---
    

    回去

    报错信息

    ---
    
    node节点加入集群中是报错:
    W0322 19:36:18.123247   13084 join.go:346] [preflight] WARNING: JoinControlPane.controlPlane settings will be ignored when control-plane flag is not set.
    [preflight] Running pre-flight checks
    	[WARNING Hostname]: hostname "node1" could not be reached
    	[WARNING Hostname]: hostname "node1": lookup node1 on 10.192.68.66:53: server misbehaving
    
    (无法访问目标主机 检查hosts文件 检查是否可以ping同目标主机 防火墙是否关闭)
    
    ---
    
    访问pod时报错:
     Unable to connect to the server: x509: certificate is valid for 10.96.0.1, 10.161.233.80, not 114.215.201.87
    (一种选择是告诉kubectl您您不想验证证书。显然,这带来了安全性问题,但我想您只是在测试,因此请按照以下步骤操作:
    
    kubectl --insecure-skip-tls-verify --context=employee-context get pods
    更好的选择是修复证书。如果通过kubeadm reset在包括主节点在内的所有节点上运行来重新初始化集群,然后执行此操作最容易
    
    kubeadm init --apiserver-cert-extra-sans=114.215.201.87
    也可以在不擦除所有内容的情况下修复该证书,但这有点棘手。以root身份在主服务器上执行以下操作:
    对于大于等于1.8的新kubernetes,此命令为:
    rm /etc/kubernetes/pki/apiserver.*
    kubeadm alpha phase certs all --apiserver-advertise-address=0.0.0.0 --apiserver-cert-extra-sans=10.161.233.80,114.215.201.87
    docker rm -f `docker ps -q -f 'name=k8s_kube-apiserver*'`
    systemctl restart kubelet
    另外,最好将dns名称添加到其中--apiserver-cert-extra-sans,以免下次发生此类问题。
    )
    
    ---
    

    配置资源清单

    配置资源清单

    清单字段理解
    资源配置格式帮助
    pod生命周期状态探测配置清单
    pod控制器配置清单
    编写资源清单

    清单字段理解

    ---
    
    
    # 创建资源的方法:
    #    aplserver仅接收JSON格式的资源定义:
    #    yaml格式提供配置清单,aplserver可自动将其转为json格式,而后再提交;
    # 大部分资源的配置清单(有5个一级字段组成):
    #    (1) apiVersion:group/version
    #         $ kubectl api-version
    #
    #    (2) kind:资源类别(核心类型(Pod,ReplicaSet,Deployment,StatefulSet,Job,Cronjob...)要打算创建什么类别,注意大小写,不可自定义)
    #
    #    (3) metadata:元数据
    #             name:同一类别当中,名字必须是唯一的
    #             namespaces:属于哪个名称空间
    #             labels:标签(标签就是键值数据)
    #             annotations:资源注解
    #         
    #         每个资源引用的PATH
    #             /api/GROUP/VERSION/namespaces/NAMESPACES/TYPE/NAME
    #
    #    (4) spec:(非常重用的字段,可能会嵌套很多级字段)定义目标期望的状态,disired state
    #
    #    (5) STATUS:当前状态,current state,本字段由kubernetes集群维护
    #
    
    ---
    

    回去

    资源配置格式帮助

    ---
    
    kubectl explain pods
    
    # explain       查看资源的文档
    
    # pod这个资源怎么定义
    # FIELDS:显示可以有很多字段可以用,字段后面有很多需求:
    #    <[]Object>(对象)表示需要嵌套三级字段,可以在进行查看,中括号表示对象列表,需要加-(横线指定),(表示对象可以出现多个)
    #    -required-,表示此字段为必选字段
    #    <[]string>(字串),中括号表示字串列表(字符串类型的数组),所有的列表数据都可以使用[]中括号表达,比如命令["/bin/sh","-c""sleep 3600"]
    #    <map[string]string>,map表示键值组成的映射,可以有多个不需要加-(是映射不是列表),所有映射数据都可以使用{}花括号表达,比如标签 {app: nginx,tier: front}
    
    
    ---
    
    kubectl explain pods.spec
    # pod下的spec如何定义(套娃行为)
    
    
    ---
    
    kubectl explain pods.spec.containers
    # pod下的spec下containers如何定义,(严重套娃行为)
    
    ---
    
    kubectl explain pods.spec.containers.livenessProbe
    # pod下的spec下containers下livenessProbe如何定义,(疯狂套娃行为)
    
    ---
    

    pod五个字段

    apiVersion
    kind
    metadata
    spec
    status

    pod控制器

    ReplicaSet(rs)
    Deployment(deploy)
    DaemonSet(ds)
    Service(svc)

    回去

    apiVersion

    ---
    
    # apiVersion <string>
    #     APIVersion定义了此对象表示形式的版本控制架构。 服务器应将已识别的模式转换为最新的内部值,并可能拒绝无法识别的值。 更多信息:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
    
    ---
    

    回去

    kind

    ---
    
    # kind	<string>
    #     Kind是一个字符串值,表示此对象表示的REST资源。 服务器可以从客户端向其提交请求的端点推断出这一点。 无法更新。 在CamelCase中。 更多信息:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
    
    ---
    

    回去

    metadata

    ---
    
    # metadata	<Object>
    #     标准对象的元数据。 更多信息:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
    
    ---
    

    metadata.annotations

    回去

    metadata.annotations

    ---
    
    # annotations	<map[string]string>
    # 资源注解与标签不一样,不能用于挑选资源对象,仅用于为对象提供“元数据”
    # kejigongsi/created-by: cluster admin
    # kejigongsi组织,created-by: 键,(比如这个资源是谁创建的),cluster admin值(比如管理员)
    
    # 注释是与资源一起存储的非结构化键值映射,可以由外部工具设置该资源来存储和检索任意元数据。 它们不可查询,在修改对象时应保留它们。 更多信息:http://kubernetes.io/docs/user-guide/annotations
    
    
    ---
    

    回去

    spec

    ---
    
    # spec	  <Object>
    # pod所需行为的规范。 更多信息:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
    
    
    ---
    

    containers(必需)
    nodeName
    nodeSelector
    restartPolicy

    回去

    containers

    ---
    
    #   containers	<[]Object> -required-
    #     属于该容器的容器列表。 当前无法添加或删除容器。 豆荚中必须至少有一个容器。 无法更新。
    
    ---
    

    containers.name(必需)
    containers.image
    containers.imagePullPolicy
    containers.ports
    containers.args
    containers.command
    containers.env
    containers.livenessProbe(探测容器是否处于存活状态)
    containers.readinessProbe(探测容器中的程序是否能够正常提供服务)
    containers.lifecycle

    回去

    nodeName

    ---
    
    # nodeName	<string>
    
    # 直接运行再指定节点上
    
    # NodeName是将此pod调度到特定节点上的请求。 如果它是非空的,则调度程序会简单地将此Pod调度到该节点上,前提是它符合资源要求。
    
    ---
    

    回去

    nodeSelector

    ---
    
    # nodeSelector	<map[string]string>
    
    # pod自会运行再拥有指定标签的nodes节点上
    
    # NodeSelector是一个选择器,必须为true才能使Pod适应节点。 选择器必须与节点的标签相匹配,才能在该节点上调度容器。 更多信息:https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
    
    ---
    

    回去

    restartPolicy

    ---
    
    # restartPolicy	 <string>
    # 重新启动容器中所有容器的策略。 
    Always(必须重启,总是重启,一旦pod中的容器挂了,重启),
    OnFailure(只有pod中容器状态为错误时才重启,正常终止的不重启)
    Never (始终不重启)。 默认为始终。 更多信息:https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
    
    ---
    

    回去

    containers.name

    ---
    
    # name	 <string> -required-
    #      指定为DNS_LABEL的容器的名称。 容器中的每个容器必须具有唯一的名称(DNS_LABEL)。 无法更新。
    
    ---
    

    回去

    containers.image

    ---
    
    # image	  <string>
    # Docker映像名称。 更多信息:
    #      https://kubernetes.io/docs/concepts/containers/images此字段是可选的,以允许更高级别的配置管理默认或覆盖工作负载控制器(如Deployments和StatefulSets)中的容器映像。
    
    ---
    

    回去

    containers.imagePullPolicy

    ---
    
    # imagePullPolicy	<string>
    # 图像拉动策略。 Always(总是去下载,本地有或者没有这个镜像,总是去仓库中下载),Never(总是不下载,本地有镜像就使用,本地没有镜像也不下载,需要用户手动拖镜像),IfNotPresent(不存在就下载,本地有镜像就使用,本地没有镜像就下载)。 如果指定了:latest标签,则默认为Always,否则为IfNotPresent。 无法更新。更多信息:
          https://kubernetes.io/docs/concepts/containers/images#updating-images
    
    ---
    

    回去

    containers.ports

    ---
    
    # ports	<[]Object>
    # (主要是参考信息,并不能起到真正意义上的暴露端口的作用)
    # 要从容器公开的端口列表。 在此处公开端口可为系统提供有关容器使用的网络连接的其他信息,但主要是参考信息。 在此未指定端口并不能防止该端口被暴露。 任何从容器中侦听默认“ 0.0.0.0”地址的端口都可以从网络访问。 无法更新。
    
    ---
    

    containers.ports.name
    containers.containerPort(必需)

    回去

    containers.ports.name

    ---
    
    # name	<string>
    # 如果指定,则该名称必须是IANA_SVC_NAME,并且在pod中是唯一的。 连网中的每个命名端口必须具有唯一的名称。 服务可以引用的端口的名称。
    
    ---
    

    回去

    containers.containerPort

    ---
    
    # containerPort	<integer> -required-
    # 在Pod的IP地址上公开的端口号。 这必须是一个有效的端口号,0 <x <65536。
    
    ---
    

    回去

    containers.args

    ---
    
    # args	<[]string>
    # (如果定义了args,将会覆盖镜像定义的CMD)
    
    # (entrypoint)入口点的参数。 如果未提供,则使用docker映像的CMD。 变量引用$(VAR_NAME)使用容器的环境进行扩展。 如果无法解析变量,则输入字符串中的引用将保持不变。 $(VAR_NAME)语法可以使用双$$来转义,即:$$(VAR_NAME)。 无论变量是否存在,转义引用都将永远不会扩展。 无法更新。 更多信息:https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
    
    ---
    

    回去

    containers.command

    ---
    
    # command	<[]string>
    # (如果定义了command,将会覆盖镜像定义的ENTRYPOINT和CMD)
    
    # (entrypoint)入口点数组。 不在外壳内执行。 如果未提供,则使用docker映像的ENTRYPOINT。 变量引用$(VAR_NAME)使用容器的环境进行扩展。 如果无法解析变量,则输入字符串中的引用将保持不变。 $(VAR_NAME)语法可以使用双$$来转义,即:$$(VAR_NAME)。 无论变量是否存在,转义引用都将永远不会扩展。 无法更新。 更多信息:https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
    
    ---
    

    回去

    containers.env

    ---
    
    # env	 <[]Object>
    # 要在容器中设置的环境变量列表。 无法更新。
    
    ---
    

    containers.env.name(必需)
    containers.env.value

    回去

    containers.env.name

    ---
    
    # name	<string> -required-
    # 环境变量的名称。 必须为C_IDENTIFIER。
    
    ---
    

    回去

    containers.env.value

    ---
    
    # value	<string>
    # 变量引用$(VAR_NAME)使用容器中先前定义的环境变量和任何服务环境变量进行扩展。 如果无法解析变量,则输入字符串中的引用将保持不变。 $(VAR_NAME)语法可以使用双$$来转义,即:$$(VAR_NAME)。 无论变量是否存在,转义引用都将永远不会扩展。 默认为“”。
    
    ---
    

    回去

    containers.livenessProbe

    ---
    
    # livenessProbe	<Object>
    # 定期检查容器的活动性。 如果探测失败,容器将重新启动。 无法更新。 更多信息:https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
    
    ---
    

    containers.livenessProbe.exec(执行指定要采取的行动)
    containers.livenessProbe.failureThreshold(探测几次算真正失败)
    containers.livenessProbe.httpGet(指定要执行的http请求。)
    containers.livenessProbe.initialDelaySeconds(延迟探测时间,保证容器初始化完成后再探测)
    containers.livenessProbe.periodSeconds(探测几次算真正失败,的时间间隔)
    containers.livenessProbe.tcpSocket(指定涉及TCP端口的操作)
    containers.livenessProbe.timeoutSeconds(探测超时,始终没有相应等多久)

    回去

    containers.livenessProbe.exec

    ---
    
    # exec	<Object>
    # 应指定以下一项,并且仅其中之一。 执行指定要采取的行动。
    
    ---
    

    回去

    containers.livenessProbe.failureThreshold

    ---
    
    # failureThreshold	<integer>
    # (探测几次都失败,默认是3个,最小值为1,连续3次失败才认为真失败了)
    
    # 成功后将被视为探针的最小连续失败数。 默认值为3。最小值为1。
    
    ---
    

    回去

    containers.livenessProbe.httpGet

    ---
    
    # httpGet	<Object>
    # HTTPGet指定要执行的http请求。
    
    ---
    

    containers.livenessProbe.httpGet.host
    containers.livenessProbe.httpGet.httpHeaders
    containers.livenessProbe.httpGet.path
    containers.livenessProbe.httpGet.port(必需)
    containers.livenessProbe.httpGet.scheme

    回去

    containers.livenessProbe.httpGet.host

    ---
    
    #   host	<string>
    #     要连接的主机名,默认为Pod IP。 您可能想在httpHeaders中设置“主机”。
    
    
    ---
    

    回去

    containers.livenessProbe.httpGet.httpHeaders

    ---
    
    #   httpHeaders	<[]Object>
    #     要在请求中设置的自定义标头。 HTTP允许重复的标头。
    
    
    ---
    

    回去

    containers.livenessProbe.httpGet.path

    ---
    
    #  path	<string>
    #    HTTP服务器上的访问路径(PATH/index.html文件路径)。
    
    ---
    

    回去

    containers.livenessProbe.httpGet.port

    ---
    
    #   port	<string> -required-
    #     容器上要访问的端口的名称或端口号。 数字必须在1到65535之间。名称必须是IANA_SVC_NAME。注意如果暴露端口可以使用名称比如(http)
    
    
    ---
    

    回去

    containers.livenessProbe.httpGet.scheme

    ---
    
    #   scheme	<string>
    #     用于连接到主机的方案。 默认为HTTP。
    
    
    ---
    

    回去

    containers.livenessProbe.initialDelaySeconds

    ---
    
    # initialDelaySeconds	<integer>
    # (延迟探测时间,保证容器初始化完成后再探测,默认容器已启动就进行探测,容器启动但是不能确保容器内的主进程启动了)
    
    # 容器启动后开始活动探测之前的秒数。 更多信息:https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
    
    ---
    

    回去

    containers.livenessProbe.periodSeconds

    ---
    
    # periodSeconds	<integer>
    # (周期探测时长,默认为10秒。 最小值为1。)
    
    # 执行探测的频率(以秒为单位)。 默认为10秒。 最小值为1。
    
    ---
    

    回去

    containers.livenessProbe.tcpSocket

    ---
    
    # tcpSocket	<Object>
    # TCPSocket指定涉及TCP端口的操作。 尚不支持TCP挂钩
    
    ---
    

    回去

    containers.livenessProbe.timeoutSeconds

    ---
    
    # timeoutSeconds	<integer>
    # (探测超时,时长默认值为1秒。最小值为1)
    
    # 探测超时之前经过的秒数。 默认值为1秒。最小值为1。更多信息:https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
    
    ---
    

    回去

    containers.readinessProbe

    ---
    
    # readinessProbe	<Object>
    #(服务就绪探测)
    
    # 定期调查容器服务准备情况。 如果探测失败,容器将从服务端点中删除。 无法更新。 更多信息:https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
    
    ---
    

    回去

    containers.lifecycle

    ---
    
    # lifecycle	<Object>
    
    # 管理系统响应容器生命周期事件应采取的措施。 无法更新。
    
    ---
    

    containers.lifecycle.postStart
    containers.lifecycle.preStop

    回去

    containers.lifecycle.postStart

    ---
    
    # postStart	<Object>
    # 容器被创建之后,立即执行的操作,如果执行失败了,容器会终止并重启,而重启与否取决于容器的重启策略
    
    # 创建容器后立即调用PostStart。 如果处理程序失败,则容器将根据其重新启动策略终止并重新启动。 容器块的其他管理,直到挂钩完成
    
    ---
    

    回去

    containers.lifecycle.preStop

    ---
    
    # preStop	<Object>
    # 对应的pod被终止之前立即执行的命令,命令执行完了,pod才会终止
    
    # 由于API请求或管理事件(例如,活动/启动探针故障,抢占,资源争用等)而终止容器之前,会立即调用PreStop。如果容器崩溃或退出,则不会调用处理程序。 终止的原因已传递给处理程序。 在执行PreStop挂钩之前,Pod的终止宽限期倒计时开始。 无论处理程序的结果如何,容器最终都将在Pod的终止宽限期内终止。 容器块的其他管理,直到挂钩完成或直到终止宽限期为止
    
    ---
    

    回去

    status

    ---
    
    #   status	<Object>
    #      最近观察到的容器状态。 该数据可能不是最新的。由系统填充。 只读。 更多信息:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
    
    ---
    

    回去

    ReplicaSet

    ---
    
    # ReplicaSet 缩写(rs)确保在任何给定时间运行指定数量的Pod副本。此控制器所在的群组VERSION:  apps/v1,不在是核心组v1
    
    
    ---
    

    ReplicaSet.spec

    回去

    ReplicaSet.spec

    ---
    
    # spec	<Object>
    # Spec定义了ReplicaSet所需行为的规范。
    
    ---
    

    ReplicaSet.spec.replicas
    ReplicaSet.spec.selector(必需)
    ReplicaSet.spec.template

    回去

    ReplicaSet.spec.replicas

    ---
    
    # replicas	<integer>
    # 副本数是所需副本数。 这是区分显式零和未指定的指针。 默认为1。
    
    ---
    

    回去

    ReplicaSet.spec.selector

    ---
    
    # selector	<Object> -required-
    # 选择器是对容器的标签查询,应与副本数匹配。 标签键和必须匹配的值才能被此副本集控制。 它必须与Pod模板的标签匹配。
    
    ---
    

    ReplicaSet.spec.matchExpressions
    ReplicaSet.spec.matchLabels

    回去

    ReplicaSet.spec.matchExpressions

    ---
    
    # matchLabels是{key,value}对的映射。 matchLabels映射中的单个{key,value}等同于matchExpressions的元素,其key字段为“ key”,运算符为“ In”,而values数组仅包含“ value”。 要求已进行AND运算。
    
    ---
    

    回去

    ReplicaSet.spec.matchLabels

    ---
    
    # matchExpressions	<[]Object>
    
    # matchLabels	<map[string]string>
    # 模板是描述如果检测到不足的副本将创建的容器的对象。此下面于pod的创建字段大致相同,metadata和spec
    
    ---
    

    回去

    ReplicaSet.spec.template

    ---
    
    # template	<Object>
    # matchExpressions是标签选择器要求的列表。 要求已进行AND运算。
    
    ---
    

    回去

    Deployment

    ---
    
    # Deployment 缩写(deploy)部署启用Pod和ReplicaSets的声明式更新。。此控制器所在的群组VERSION:  apps/v1,不在是核心组v1
    
    # 如果没有使用ReplicaSets,使用Deployment 此字段 ,ReplicaSets 也会被创建
    
    ---
    

    Deployment.spec

    回去

    Deployment.spec

    ---
    
    # spec	<Object>
    # 指定部署所需的行为。
    
    ---
    

    大多数于ReplicaSet控制器字段相同

    Deployment.spec.replicas
    Deployment.spec.selector(必需)
    Deployment.spec.strategy
    Deployment.spec.revisionHistoryLimit
    Deployment.spec.paused
    Deployment.spec.template(必需)

    回去

    replicas

    ---
    
    # replicas   <integer>
    # 所需pod的数量。 这是一个区分显式零和未指定的指针。 默认为1。
    
    ---
    

    回去

    selector

    ---
    
    # selector  <<Object> -required-
    # pods标签选择器。 被其选择的pods的现有副本集将受到此部署的影响。 它必须与Pod模板的标签匹配。
    
    ---
    

    Deployment.spec.selector.matchLabels

    回去

    matchLabels

    ---
    
    # matchLabels    <map[string]string>
    # matchLabels是{key,value}对的映射。 matchLabels映射中的单个{key,value}等同于matchExpressions的元素,其key字段为“ key”,运算符为“ In”,而values数组仅包含“ value”。 要求已进行AND运算。
    
    ---
    

    回去

    strategy

    ---
    
    # strategy	<Object>
    # 用于用新的Pod替换现有Pod的部署策略。
    
    ---
    

    Deployment.spec.strategy.rollingUpdate
    Deployment.spec.strategy.type

    回去

    Deployment.spec.strategy.rollingUpdate

    ---
    
    # rollingUpdate	<Object>
    # 仅在type = RollingUpdate时使用
    
    # 滚动更新配置参数。 仅在DeploymentStrategyType = RollingUpdate时显示。
    
    ---
    

    Deployment.spec.strategy.rollingUpdate.maxSurge
    Deployment.spec.strategy.rollingUpdate.maxUnavailable

    回去

    revisionHistoryLimit

    ---
    
    # revisionHistoryLimit	<integer>
    # (我们要做滚动更新以后,最多再历史当中保存多少个历史版本,默认为10)
    
    # 要保留以允许回滚的旧ReplicaSet的数量。 这是一个区分显式零和未指定的指针。 默认为10
    
    ---
    

    回去

    Deployment.spec.paused

    ---
    
    # paused	<boolean>
    # (一启动就暂停,可以控制暂停)
    
    # 表示部署已暂停。
    
    ---
    

    回去

    Deployment.spec.template

    ---
    
    # template	<Object> -required-
    # (根据模板创建pod,于ReplicaSet创建方式相同)
    
    # 模板描述了将要创建的pod。
    
    ---
    

    回去

    Deployment.spec.strategy.rollingUpdate.maxSurge

    ---
    
    # maxSurge	<string>
    # (对应的更新过程当中,最多能超出你所指定的目标副本数几个,有两种取值方式,第一直接指明数量,第二指明百分比,原本是5个最多超过百分之20就是多1个,百分之40就是多2个)
    
    # 可以在所需的Pod数量之上安排的最大Pod数量。 值可以是绝对数(例如5)或所需豆荚的百分比(例如10%)。 如果MaxUnavailable为0,则不能为0。绝对值是通过四舍五入从百分比计算得出的。 默认为25%。 示例:将其设置为30%时,可以在滚动更新开始时立即按比例放大新的ReplicaSet,以使新旧Pod的总数不超过所需Pod的130%。 一旦旧的Pod被杀死,就可以进一步扩展新的ReplicaSet,以确保更新期间任何时候运行的Pod总数最多为所需Pod的130%。
    
    ---
    

    回去

    Deployment.spec.strategy.rollingUpdate.maxUnavailable

    ---
    
    # maxUnavailable	<string>
    # (最多有几个不可用,一共有5个副本,最多有1个不可用,那就是最少要有4个可用)
    
    # 更新期间可能不可用的Pod的最大数量。 值可以是绝对数(例如5)或所需豆荚的百分比(例如10%)。 绝对数字是通过四舍五入从百分比中得出的。 如果MaxSurge为0,则不能为0。默认值为25%。 示例:将其设置为30%时,可以在滚动更新开始时立即将旧的ReplicaSet缩小为所需容器的70%。 一旦准备好新的Pod,就可以进一步缩小旧的ReplicaSet,然后再扩展新的ReplicaSet,以确保更新期间始终可用的Pod总数至少为所需Pod的70%。
    
    ---
    

    回去

    Deployment.spec.strategy.type

    ---
    
    # type	<string>
    # (一种重建式更新,删一个,重建一个,一种RollingUpdate滚动更新,定义此参数,可以用rollingUpdate	定义)
    
    # 部署类型。 可以是“重新创建”或“ RollingUpdate”。 默认值为RollingUpdate。
    
    ---
    

    回去

    DaemonSet

    ---
    
    # DaemonSet表示守护程序集的配置。
    
    ---
    

    回去

    Service

    ---
    # Service
    # 服务是软件服务(例如mysql)的命名抽象,包括代理侦听的本地端口(例如3306)和选择器,该选择器确定哪些Pod将响应通过代理发送的请求。
    
    ---
    

    Service.spec

    回去

    Service.spec

    ---
    # spec	<Object>
    # 规范定义了服务的行为。
    
    ---
    

    Service.spec.clusterIP
    Service.spec.type
    Service.spec.ports
    Service.spec.selector

    回去

    Service.spec.clusterIP

    ---
    
    # clusterIP	<string>
    # (服务ip一般是动态的,如果要使用固定ip使用此字段,创建前指定 创建后就改不了)
    
    # clusterIP是服务的IP地址,通常由主服务器随机分配。 如果地址是手动指定的,并且未被其他人使用,则该地址将分配给服务; 否则,服务创建将失败。 无法通过更新更改此字段。 有效值为“ None”,空字符串(“”)或有效IP地址。 不需要代理时,可以将“无”指定为无头服务。 仅适用于ClusterIP,NodePort和LoadBalancer类型。 如果类型是,则忽略
    
    ---
    

    回去

    Service.spec.type

    ---
    
    # type	<string>
    #(工作模式一种有4中,
    # 第一默认为ClusterIP仅用于集群内的ip,
    
    # 第二NodePort接入集群外部的流量,
    
    # 第三LoadBalancer表示把kubernetes部署到虚拟机上,而虚拟机是工作再云环境上,而我们的云环境支持 LBaaS负载均衡以及服务的一键调用创建负载均衡器时使用,自动触发再外部创建一个负载均衡器,
    
    # 第四种ExternalName表示把集群外部的服务引用到集群内部来,再集群内部直接使用)
    
    # 类型确定如何公开服务。 默认为ClusterIP。 有效选项是ExternalName,ClusterIP,NodePort和LoadBalancer。 “ ExternalName”映射到指定的externalName。 “ ClusterIP”为端点分配一个群集内部的IP地址以进行负载平衡。 端点由选择器确定,如果未指定,则由端点对象的手动构造确定。 如果clusterIP为“ None”,则不分配虚拟IP,并且将端点发布为一组端点而不是稳定IP。 “ NodePort”建立在ClusterIP上,并在路由到clusterIP的每个节点上分配一个端口。 “ LoadBalancer”建立在NodePort上,并创建一个外部负载均衡器(如果当前的云支持),该负载均衡器路由到clusterIP。
    
    ---
    

    回去

    Service.spec.selector

    ---
    
    # selector	<map[string]string>
    # (仅支持等值关系)
    
    #使用标签键和与该选择器匹配的值将服务流量路由到Pod。 如果为空或不存在,则假定该服务具有管理其端点的外部进程,而Kubernetes不会对其进行修改。 仅适用于ClusterIP,NodePort和LoadBalancer类型。 如果type为ExternalName,则忽略。
    
    ---
    

    回去

    Service.spec.ports

    ---
    
    # ports	<[]Object>
    
    # 此服务公开的端口列表。忽略
    
    ---
    

    Service.spec.ports.name
    Service.spec.ports.nodePort
    Service.spec.ports.port(必需)
    Service.spec.ports.targetPort

    回去

    Service.spec.ports.name

    ---
    
    # name	<string>
    
    # 服务中此端口的名称。 这必须是DNS_LABEL。 ServiceSpec中的所有端口必须具有唯一的名称。 考虑服务的端点时,必须与EndpointPort中的“名称”字段匹配。 如果在此服务上仅定义了一个ServicePort,则为可选。
    ---
    

    回去

    Service.spec.ports.nodePort

    ---
    
    # nodePort	<integer>
    # (节点端口,可以不用指,只有类型为LoadBalancer时才有用)
    
    # 当类型= NodePort或LoadBalancer时,在其上公开此服务的每个节点上的端口。 通常由系统分配。 如果指定,则在未使用时将其分配给服务,否则服务创建将失败。 如果此服务的ServiceType需要一个端口,则默认值为自动分配端口。
    ---
    

    回去

    Service.spec.ports.port

    ---
    
    # port	<integer> -required-
    #(当前服务端口,对外提供服务的端口)
    
    # 此服务将公开的端口。
    
    ---
    

    回去

    Service.spec.ports.targetPort

    ---
    
    # targetPort	<string>
    #(容器的端口)
    
    # 服务所针对的Pod上要访问的端口号或端口号。该端口号必须在1到65535之间。名称必须是IANA_SVC_NAME。 如果这是一个字符串,它将在目标Pod的容器端口中查找为一个命名端口。 如果未指定,则使用“端口”字段的值(身份映射)。 对于clusterIP = None的服务,此字段将被忽略,应将其省略或设置为等于“ port”字段。
    
    ---
    

    回去

    pod生命周期状态探测配置清单

    ---
    
    # Pod生命周期中的重要行为:
    #    初始化容器
    #    容器探测:
    #        liveness(探测容器是否处于存活状态)
    #        readlness(探测容器中的程序是否能够正常提供服务)
    
    ---
    
    #  liveness(探测容器是否处于存活状态),如果探针命令,探测失败,容器重启,kubectl describe pods livenessc-pod查看Reason(原因),Exit Code(退出码),Ready(准备),Restart Count(重新启动计数)
    
    apiVersion: v1
    kind: Pod
    metadata: 
        name: livenessc-pod
        namespace: default
    spec:
        containers:
        -    name: liveness-exec-container
             image: busybox:latest
             imagePullPolicy: IfNotPresent
             command: ["/bin/sh","-c","touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 3600"]
             livenessProbe:
                exec:
                    command: ["test","-e","/tmp/healthy"]
                initialDelaySeconds: 1
                periodSeconds: 3
        -    name: liveness-httpdget-container
             image: nginx:1.14.2
             imagePullPolicy: IfNotPresent
             ports:
             -    name: http
                  containerPort: 80
             livenessProbe:
                httpGet:
                    port: http
                    path: /index.html
                initialDelaySeconds: 1
                periodSeconds: 3
    
    ---
    
    # 测试:
    # command    字段touch了一个文件,等30秒后,删除文件,再等3600秒
    
    # 测试探测效果:
    # livenessProbe    探测容器状态,如果探测失败,容器将重新启动
    # exec    使用command方法,探测/tmp/healthy此文件是否存在
    #    过程: (1)容器启动,,文件存在,30秒后文件删除,文件存在,容器重启
    #          (2)容器启动,,文件存在,30秒后文件删除,文件存在,容器重启
    #          (3)容器启动,,文件存在,30秒后文件删除,文件存在,容器重启
    #          (4)状态为启动失败,继续会重启,重启时间间隔为10秒,20秒,40秒,80秒,160秒,300秒,5分钟
    # initialDelaySeconds    延迟探测1秒,保证容器初始化完成后再探测
    # periodSeconds    探测3算真正失败,3次以后这容器就不在是就绪状态
    # httpGet网页探测测试,可以接入容器中把nginx的index.heml,在/usr/share/nginx/html/index.html删除,查看状态
    
    ---
    
    # readlness(探测容器中的程序是否能够正常提供服务,比如nginx提供的网页,如果删除,服务在,网页访问不到,检测到文件不在就绪,文件重新创建,检测到文件在,就切换到就绪,不重启容器)探测方式与liveness类似,kubectl describe pods readlness-pod查看Ready状态是真还是假
    
    apiVersion: v1
    kind: Pod
    metadata: 
        name: readlness-pod
        namespace: default
    spec:
        containers:
        -    name: readlness-httpdget-container
             image: nginx:1.14.2
             imagePullPolicy: IfNotPresent
             ports:
             -    name: http
                  containerPort: 80
             readinessProbe:
                httpGet:
                    port: http
                    path: /index.html
                initialDelaySeconds: 1
                periodSeconds: 3
    
    ---
    

    回去

    pod控制器配置清单

    ---
    
    ################### ReplicaSet
    
    apiVersion: apps/v1
    kind: ReplicaSet
    metadata:
        name: nginx-pod
        namespace: default
    spec:
        replicas: 2
        selector:
            matchLabels:
                app: web
                release: canary
        template:
            metadata:
                name: nginxpod
                labels: 
                    app: web
                    release: canary
                    environment: qa
            spec:
                containers:
                -    name: nginx-container
                     image: nginx:1.14.2
                     ports:
                     -    name: http
                          containerPort: 80
            
    
    # pod模板中的pod名是不生效的,他会跟控制器的名字,并随机给字符串作为pod名称
    
    # pod模板中期望是存在两个pod,删除一个会立即重新创建一个
    
    # pod根据模板多退少补(根据标签选择器决定,三个一样标签的删除一个pod,少一个就启动一个pod)基于标签控制需要使用复杂条件,一旦标签冲突就悲剧了
    
    # pod生命周期有控制器决定,一旦挂了会立即补上
    
    ---
    
    ################### Deployment
    
    apiVersion: apps/v1
    kind: Deployment
    metadata:
        name: nginx-deployment
        namespace: default
    spec:
        replicas: 2
        selector:
            matchLabels:
                app: web
                release: canary
        template:
            metadata:
                labels:
                    app: web
                    release: canary
            spec:
                containers:
                -    name: nginx-pod
                     image: nginx:1.14.2
                     ports:
                     -    name: http
                          containerPort: 80
    
    # 注意给的标签要,如果键相同,值也要相同
    
    # 如果kubectl get deploy 显示没有就绪,创建时也没报错,查看镜像是否正确
    
    # 创建后rs也被创建起来了kubectl get rs
    
    # kubectl get pod -l app=web -w 监视pod更新
    
    # 修改yaml文件pod镜像版本号,kubectl apply -f 更新pod
    
    # kubectl get rs会保留之前的版本信息,以便随时回滚
    
    
    ---
    
    ################### DaemonSet
    
    apiVersion: apps/v1
    kind: Deployment
    metadata:
       name: redis
       namespace: default 
    spec:
       replicas: 1
       selector:
           matchLabels:
               app: redis
               role: logstor
       template:
           metadata:
               labels:
                   app: redis
                   role: logstor
           spec:
               containers:
               -    name: redis
                    image: redis:4.0-alpine
                    ports:
                    -    name: redis
                         containerPort: 6379
           
    ---
    
    apiVersion: apps/v1
    kind: DaemonSet
    metadata:
        name: filebeat-ds
        namespace: default
    spec:
        selector:
            matchLabels:
                app: filebeat
                release: stable
        template:
            metadata:
                labels:
                    app: filebeat
                    release: stable
            spec:
                containers:
                -    name: filebeat
                     image: ikubernetes/filebeat:5.6.5-alpine
                     ports:
                     -    name: http
                          containerPort: 80
                     env:
                     -    name: REDIS_HOST
                          value: redis.default.svc.cluster.local
                     -    name: REDIS_LOG_LEVEL
                          value: info
    
    
    # 变量名如果错误会进行重启
    
    # REFIS_HOST 日志主机
    # redis(服务名).default(名称空间).svc.cluster.local(本地当前kubernetes集群的内建的本地域名后缀)
    
    # REDIS_LOG_LEVEL 日志级别
    
    ---
    
    ################### Service
    
    apiVersion: v1
    kind: Service
    metadata: 
        name: redis
        namespace: default
    spec:
        selector:
            app: redis
            role: logstor
        clusterIP: 10.97.97.97
        type: ClusterIP
        ports:
        -    port: 6379
             targetPort: 6379
    
    
    # port: 6379  service ip的端口
    # targetPort: 6379 pod ip上的端口
    # kubectl get svc 查看
    
    apiVersion: v1
    kind: Service
    metadata:
        name: nginx
        namespace: default
    spec:
        selector:
            app: web
            release: canary
        clusterIP: 10.99.99.99
        type: NodePort
        ports:
        -    port: 80
             targetPort: 80
             nodePort: 30080
    
    #  nodePort: 30080  不指也可以动态分配,如果指定保证端口号没有被占用,否者会冲突
    # type: NodePort 集群外可以对这台主机进行访问
    # 循环访问命令 while true; do curl http://192.168.0.5:30080; sleep 1; done
    
    
    ---
    

    回去

    编写资源清单

    ---
    #########################注意:
    # 注意大小写
    # apiVersion和kind: Pod的V是大写,Pod的P是大写,注意如果是复制的,注意字段名是否完整
    # name: pod-demo,pod名字不可有下划线
    
    apiVersion: v1
    kind: Pod
    metadata:
        name: pod-demo
        namespace: default
        labels:
          app: nginx
          tier: fronttend
        annotations:
          kejigongsi/created-by: cluster admin
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.1
        ports:
        - name: http
          containerPort: 80
        - name: https
          containerPort: 443
      - name: busybox
        image: busybox:latest
        imagePullPolicy: IfNotPresent
        command:
        - "/bin/sh"
        - "-c"
        - "sleep 3600"
      nodeSelector:
        disktype: ssd
    
    
    ---
    

    回去

  • 相关阅读:
    【leetcode】1215.Stepping Numbers
    【leetcode】1214.Two Sum BSTs
    【leetcode】1213.Intersection of Three Sorted Arrays
    【leetcode】1210. Minimum Moves to Reach Target with Rotations
    【leetcode】1209. Remove All Adjacent Duplicates in String II
    【leetcode】1208. Get Equal Substrings Within Budget
    【leetcode】1207. Unique Number of Occurrences
    【leetcode】689. Maximum Sum of 3 Non-Overlapping Subarrays
    【leetcode】LCP 3. Programmable Robot
    【leetcode】LCP 1. Guess Numbers
  • 原文地址:https://www.cnblogs.com/hao-ran/p/11614191.html
Copyright © 2011-2022 走看看