编程知识 cdmana.com

1. K8s overview, installation, term explanation, resource list

One 、k8s summary

1、 brief introduction

  • Kubernetes It's an open source , It is used to manage containerized applications on multiple hosts in the cloud platform ,Kubernetes The goal is to make the deployment of containerized applications simple and efficient (powerful),Kubernetes Provides application deployment , planning , to update , A mechanism of maintenance , because k and s There are 8 Letters , So for short k8s
  • The traditional way of application deployment is to install applications through plug-ins or scripts . The disadvantage of this is the operation of the application 、 To configure 、 management 、 All lifecycles will be bound to the current operating system , This is not conducive to the application update / Rollback and other operations , Of course, some functions can also be realized by creating virtual machines , But the virtual machine is very heavy , Not good for portability
  • The new way is to deploy containers , Each container is isolated from each other , Each container has its own file system , Processes between containers don't affect each other , Be able to distinguish computing resources . Compared to virtual machines , Containers can be deployed quickly , Because of the container and bottom facilities 、 Machine file system decoupled , So it can be in different clouds 、 Migration between different versions of operating systems
  • Kubernetes yes Google An open source container choreography engine , It supports automated deployment 、 Large scale scalability 、 Apply containerization Management . When you deploy an application in a production environment , It is usually necessary to deploy multiple instances of the application in order to load balance the application requests
  • stay Kubernetes in , We can create multiple containers , Each container runs an application instance , Then through the built-in load balancing strategy , Realize the management of this group of application instances 、 Find out 、 visit , And these details do not require the operation and maintenance personnel to carry out complex manual configuration and processing
  • kubernetes The predecessor was Borg,Borg It's the cluster manager , In its system , Running clusters , Each cluster can be made up of thousands of server connections ,Borg Hundreds and thousands of submissions from many applications are being processed all the time Job, For these Job Receive 、 Dispatch 、 start-up 、 stop it 、 Restart and monitor . just as Borg It is said in the paper that ,Borg Provides 3 Big advantage
    • Hidden resource management and error handling , Users only need to focus on Application Development
    • High service availability 、 Highly reliable
    • Load can be run in a cluster of thousands of machines

2、 characteristic

  • Kubernetes One of the core features is the ability to manage containers independently to ensure that containers in the cloud platform run according to the expected state of users ( For example, users want to make apache Has been running , Users don't need to care about how to do ,Kubernetes Will automatically monitor , Then go and restart , newly build , All in all , Give Way apache Always provide services ), Administrators can load a microservice , Let the planner find the right place , meanwhile ,Kubernetes It also improves the tools and humanization of the system , So that users can easily deploy their own applications ( It's like canary deployments)
  • Automatic boxing
    • The resource configuration of application running environment based on container requires automatic deployment of application container
  • Self repair ( Self healing power )
    • When the container fails , The container will be restarted when the deployed Node When the node has problems , The container is redeployed and rescheduled when the container fails the monitoring check , This container will be closed until the container is running properly , To provide services to the outside world
  • Horizontal expansion
    • By simple command 、 user UI The interface may be based on CPU And the use of resources , Scale up or tailor the application container
  • Service discovery
    • Users do not need to use additional service discovery mechanisms , Can be based on Kubernetes Its own ability to achieve service discovery and load balancing
  • Scroll to update
    • Depending on the application , Applications running on the application container , Make one-time or batch updates
  • Version rollback
    • According to the application deployment , Applications running on the application container , Instant rollback of historical version
  • Key and configuration management
    • Without having to rebuild the image , Key and application configuration can be deployed and updated , Like hot deployment
  • Storage choreography
    • Automatic storage system mount and application , Especially for stateful applications, data persistence is very important. The storage system can come from the local directory 、 Network storage (NFS、Gluster、Ceph etc. )、 Public cloud storage services
  • The batch
    • Provide one-time tasks , Timing task ; Scenarios for batch data processing and analysis

3、 framework

  • explain

    • master node
      • k8s Cluster control node , Scheduling management of the cluster , Accept requests from users outside the cluster to operate in the cluster ;Master Node from API Server、Scheduler、ClusterState Store(ETCD database ) and Controller Manager The composition of
        • API Server: The entrance to the cluster , The outside world through kubectl Tools such as , Operate the cluster
        • Schedule: Scheduler , Schedule the resources of the cluster , to pod Distribution nodes, etc
        • ETCD: Save the configuration information of the cluster , It can also be configured as a cluster , A reliable distributed key value storage service , It can store some key data for the whole distributed cluster , Assist the normal operation of distributed cluster , Recommended in the Kubernetes Use in cluster Etcd v3,v2 The version is already in Kubernetes v1.11 To discard
        • Controller MangerServer: Cluster controller , Yes pod Control , contain Replication Controller(RC) perhaps Replica Set(RS),RS Has replaced RC, Maintain the desired number of copies
    • worker node
      • Cluster work node , Run user business application container ;Worker Node contain kubelet、kube proxy and ContainerRuntime;
        • Kubelet: Directly interact with the container engine to realize the life cycle management of the container , and master Interact , Manage the current node ( It's equivalent to master Sent to node Representatives of Management )
        • Kube-proxy: Responsible for writing rules to IPTABLES、IPVS Implementation of service mapping access , Reverse agent and load balancing
    • Other plug-ins
      • COREDNS: It can be used for SVC Create a domain name IP Analysis of the corresponding relationship of
      • DASHBOARD: to K8S Cluster provides a B/S Structure access architecture
      • INGRESS CONTROLLER: The government can only achieve four levels of agency ,INGRESS It can realize seven layers of agents
      • FEDERATION: Provide a cluster center that can span multiple K8S Unified management function
      • PROMETHEUS: Provide K8S The monitoring capability of the cluster
      • ELK: Provide K8S Cluster log unified analysis intervention platform

Two 、k8s install

1、 Installation requirements

  • One or more machines , operating system CentOS7.x-86_x64( kernel 4 Best of all )( At least three , One master, Two node)
  • hardware configuration :2GB Or more RAM,2 individual CPU Or more CPU, Hard disk 30GB Or more
  • Network interworking among all machines in the cluster
  • Access to the Internet , Need to pull image ( Can't access the Internet , Soft routing can be set , Building private warehouses, etc )
  • prohibit swap Partition

2、 Installation mode

  • The current production deployment Kubernetes There are two main ways to cluster
    • kubeadm
    • Binary package
      • from github Download the distribution's binary package , Manually deploy each component , form Kubernetes colony
  • Kubeadm Lower deployment threshold , But it's a lot of detail , It's hard to troubleshoot problems . If you want to be more controllable , Binary package deployment is recommended Kubernetes colony , Although manual deployment is troublesome , You can learn a lot about how it works , It's also good for later maintenance

2.1、kubeadm install

  • Prepare the environment , Three machines , One master, Two node

    • role ip
      master 192.168.47.150
      node1 192.168.47.161
      node2 192.168.47.162
    • #  The following command is executed by all nodes 
      #  Turn off firewall 
      systemctl stop firewalld
      systemctl disable firewalld
      
      #  close selinux
      sed -i 's/enforcing/disabled/' /etc/selinux/config  #  permanent 
      setenforce 0  #  temporary 
      
      #  close swap
      swapoff -a  #  temporary 
      sed -ri 's/.*swap.*/#&/' /etc/fstab    #  permanent 
      
      #  Set the host name according to the plan 
      hostnamectl set-hostname <hostname>
      
      #  stay master add to hosts
      cat >> /etc/hosts << EOF
      192.168.47.150 k8smaster
      192.168.47.161 k8snode1
      192.168.47.162 k8snode2
      EOF
      
      #  To be bridged IPv4 Flow to iptables Chain 
      cat > /etc/sysctl.d/k8s.conf << EOF
      net.bridge.bridge-nf-call-ip6tables = 1
      net.bridge.bridge-nf-call-iptables = 1
      EOF
      sysctl --system  #  take effect 
      
      #  Time synchronization 
      # yum install chrony -y centos 8 chrony To replace the ntpdate 
      # yum install ntpdate -y
      # chrony time.windows.com
      # ntpdate time.windows.com
      #  Set the system time zone to   China / Shanghai 
      timedatectl set-timezone Asia/Shanghai
      #  Change the current  UTC  Time written to hardware clock 
      timedatectl set-local-rtc 0
      #  Restart services that depend on system time 
      systemctl restart rsyslog
      systemctl restart crond
      
  • All nodes are installed Docker/kubeadm/kubelet

    • #  install docker  And the machine starts automatically 
      $ wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo
      $ yum -y install docker-ce-18.06.1.ce-3.el7
      $ systemctl enable docker && systemctl start docker
      $ docker --version
      Docker version 18.06.1-ce, build e68fc7a
      #  Set up the mirror Accelerator 
      $ cat > /etc/docker/daemon.json << EOF
      {
        "registry-mirrors": ["https:// Own address .mirror.aliyuncs.com"]
      }
      EOF
      
    • #  Add alicloud YUM Software sources 
      $ cat > /etc/yum.repos.d/kubernetes.repo << EOF
      [kubernetes]
      name=Kubernetes
      baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
      enabled=1
      gpgcheck=0
      repo_gpgcheck=0
      gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
      EOF
      
    • #  install kubeadm,kubelet and kubectl  And the machine starts automatically 
      #  Due to frequent version updates , The version number deployment is specified here 
      $ yum install -y kubelet-1.18.0 kubeadm-1.18.0 kubectl-1.18.0
      $ systemctl enable kubelet
      
  • Deploy Kubernetes Master

    • #  Running on the master node   Because the default pull image address k8s.gcr.io No domestic access , Here is the address of Alibaba cloud image warehouse 
      $ kubeadm init \
        --apiserver-advertise-address=192.168.47.150 \
        --image-repository registry.aliyuncs.com/google_containers \
        --kubernetes-version v1.18.0 \
        --service-cidr=10.96.0.0/12 \
        --pod-network-cidr=10.244.0.0/16
      
    • #  Use kubectl Tools   After the initialization of the master node is completed , There will be this command on the interface , Copy and execute directly 
      mkdir -p $HOME/.kube
      sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
      sudo chown $(id -u):$(id -g) $HOME/.kube/config
      
  • Deploy Kubernetes node

    • #  Add new nodes to the cluster , Execute on kubeadm init Output kubeadm join command ( After the initialization of the master node is completed , There will be this command on the interface , Copy directly in node You can execute it on )
      $ kubeadm join 192.168.1.11:6443 --token esce21.q6hetwm8si29qxwn \
          --discovery-token-ca-cert-hash sha256:00603a05805807501d7181c3d60b478788408cfe6cedefedb1f97569708be9c5
      
    • #  Default token Valid for 24 Hours , When it expires , The token It's not available . Now you need to recreate token
      kubeadm token create --print-join-command
      
  • Deploy CNI The network plugin

    • #  The default image address cannot be accessed ,sed The command was changed to docker hub Mirror warehouse   If you can't download , Use local files 
      kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
      
      kubectl get pods -n kube-system
      NAME                          READY   STATUS    RESTARTS   AGE
      kube-flannel-ds-amd64-2pc95   1/1     Running   0          72s
      
  • test kubernetes colony

    • #  Create a pod  And expose the service for external access 
      $ kubectl create deployment nginx --image=nginx
      $ kubectl expose deployment nginx --port=80 --type=NodePort
      $ kubectl get pod,svc
      
    • Access address :http:// arbitrarily node Of ip: Exposed ports

2.2、 Binary package installation

  • Because binary package installation is more complex , If you are interested, please refer to the relevant documents ( The certificate information needs to be self built , In other words, the internal access of the cluster is https,kubelet and api server You need a certificate for your interaction , Otherwise, it can't interact )

3、 ... and 、 Brief concept

1、Pod

1.1、 summary

  • Pod yes k8s The smallest unit in the system that can be created and managed , It is the smallest resource object model created or deployed by users in the resource object model , Also in k8s Resource objects that run containerized applications on , Other resource objects are used to support or extend Pod Object function , For example, the controller object is used to control Pod Object's ,Service perhaps Ingress Resource objects are used to expose Pod Of the reference object ,PersistentVolume Resource objects are used for Pod Provide storage and so on ,k8s You don't deal with containers directly , It is Pod,Pod By one or more container form
  • Pod yes Kubernetes The most important concept of , every last Pod There is a special one called ” Root container “ Of Pause Containers .Pause The mirror of the container Like belonging to Kubernetes Part of the platform , except Pause Containers , Every Pod It also contains one or more closely related user business containers

1.2、 form

  • Pod The composition of :Pause( be used for Pod The containers within the shared network and shared storage , By k8s Automatically created , Think of it as a logical host ),main container Provide services , One Pod There can be multiple containers inside , The same Pod You can use it directly localhost: Port direct access (pod It doesn't exist , It's an abstract meaning )

1.3、Pod characteristic

  • Every Pod Are examples of applications , There are special ones IP

  • One Pod There can be multiple containers , Share network and storage resources with each other , Every Pod There is one of them. Pause The container holds all the container States , Through management pause Containers , Achieve management pod The effect of all containers in

  • The same Pod Containers in are always scheduled to the same location Node node , Between different nodes Pod The communication based on virtual layer 2 network technology

  • Resource sharing

    • One Pod Multiple containers in can share storage and network , Think of it as a logical host . Shared such as namespace,cgroups Or other isolated resources
    • Multiple containers share the same network namespace, So in a Pod Multiple containers in share Pod Of IP And port namespace, So a Pod Multiple containers inside can be connected through localhost To communicate , What we need to pay attention to is that different containers should not have port conflicts . Different Pod Different IP, Different Pod Before multiple containers inside , Not available IPC( If there's no special designation ) signal communication , Usually use Pod Of IP communicate
    • One Pod Multiple containers in can share storage volumes , This storage volume will be defined as Pod Part of , And can be mounted to the Pod On the file system of all containers in
  • The life cycle is short

    • Pod It belongs to components with short life cycle , such as , When Pod The node is in failure , Then the node of Pod Will be scheduled to other nodes , But it should be noted that , Rescheduled Pod It's a brand new Pod, Just like before Pod It's nothing to do with half a cent
  • Flat network

    • K8s All in the cluster Pod All in the same shared network address space , That is to say, each Pod All can be done through other Pod Of IP Address to access

1.4、Pod classification

  • Autonomous
    • Autonomous Pod By kubelet What is managed only exists in the specific Node Upper Pod, They can't go through API Server Conduct management , Can't be with ReplicationController、Deployment or DaemonSet Association , also kubelet They can't be examined for health
    • Generally speaking, there is no controller management Pod, Quit and it's over , Nobody cares
  • Controller managed Pod
    • Controller managed Pod Once created , It will be put into etcd Storage in , Is then Kubernetes Master Dispatch to a specific Node Up and bind , Then the Pod Corresponding Node Upper kubelet Processes are instantiated into a set of related Docker Container and start up . In default Condition , When Pod When one of the containers in it stops ,Kubernetes It will automatically detect this problem and restart this Pod All the containers in LiMou , If Pod Where Node Downtime , I'm going to take this Node All the Pod Rescheduling to other nodes
    • Generally speaking, it is managed by the controller Pod, If you quit, there will be controller management , Restart , Maintain the desired number of copies

2、 controller

  • The controller is used to control Pod The number of , Yes Pod Control can manage

2.1、 Controller classification

  • Deployment
    • ReplicationController Used to ensure that the number of copies of the container application is always kept at the number of user-defined copies , That is, if a container exits abnormally , Will automatically create a new Pod To replace ; And if the extra containers are recovered automatically . In the new version of Kubernetes It is recommended to use ReplicaSet To replace ReplicationControlle
    • ReplicaSet Follow ReplicationController There is no essential difference , It's just that the names are different , also ReplicaSet Support for aggregate selector
    • although ReplicaSet Can be used independently , But it is generally recommended to use Deployment To automatically manage ReplicaSet , So there is no need to worry about incompatibility with other mechanisms ( such as ReplicaSet I won't support it rolling-update but Deployment Support )
    • Created Deployment It will create the corresponding RS or RC( Through the bottom layer RS or RC Control the number of copies ), At the same time, it also provides functions such as rolling update and version rollback ( In fact, it is through different RS or RC Realized )
    • Deployment by Pod and ReplicaSet Provides a Declarative definition (declarative) Method , To replace the old one ReplicationController To facilitate the management of the application . Typical application scenarios include
      • Definition Deployment To create Pod and ReplicaSet
      • Scroll upgrade and rollback applications
      • Expand and shrink
      • Pause and resume Deployment
  • HPA
    • Horizontal Pod Autoscaling Only applicable to Deployment and ReplicaSet , stay V1 Only according to Pod Of CPU Utilization expansion , stay v1alpha In the version , Support for memory and user-defined metric Expansion and contraction capacity
  • StatefullSet
    • StatefulSet To solve the problem of stateful service ( Corresponding Deployments and ReplicaSets Is designed for stateless services ), The application scenarios include
      • Stable persistent storage , namely Pod You can still access the same persistent data after rescheduling , be based on PVC To achieve
      • Stable network logo , namely Pod After rescheduling PodName and HostName unchanged , be based on Headless Service( That is, no Cluster IP Of Service ) To achieve
      • Orderly deployment , The orderly expansion , namely Pod There is a sequence , When you deploy or extend, you do so in the order you defined ( From 0 To N-1 , The next Pod Run all before Pod Must be Running and Ready state ), be based on init containers To achieve
      • Orderly contraction , In order to delete ( From N-1 To 0 0 )
  • Job ,CronJob
    • Job Responsible for batch processing tasks , That is to say, a task that is performed only once , It guarantees one or more of the batch tasks Pod
    • Cron Job Manage time-based Job
      • Run only once at a given point in time
      • Run periodically at a given point in time

3、Service

  • Service yes Kubernetes The core concept , By creating a Service, It can provide a uniform entry address for a group of container applications with the same functions , And distribute the request load to each container application in the back end
  • Equivalent to a group of the same function Pod Provide an address for outside access , For these Pod Acting as agent ( because Pod If you remove ,RC To keep the number of copies , Will pull up a new Pod, And new Pod And the original Pod Totally different ,Ip The address is different , So you can't use Ip visit Pod), And it can also play the role of load balancing , through Pod Of lables Acting as agent
  • classification
    • ClusterIP: The cluster uses
    • NodePort: External access applications use
    • LoadBalancer: External access applications use , Public cloud

Four 、 Network communication mode

  • Kubernetes Our network model assumes that all Pod All in a flat network space that can be directly connected , This is in GCE ( Google Compute Engine ) It's a ready-made network model , Kubernetes Suppose the network already exists . And build in the private cloud Kubernetes colony , You can't assume that this network already exists . We need to implement this network hypothesis ourselves , Put... On different nodes Docker The mutual access between containers should be made first , And then run Kubernetes

  • The same Pod Between multiple containers in : localhost
    various Pod Communication between : Overlay Network
    Pod And Service Communication between : Of each node Iptables The rules

  • Flannel yes CoreOS Team directed Kubernetes Design of a network planning service , Simply speaking , Its function is to let different node hosts in the cluster create Docker Containers all have the unique virtual of the whole cluster IP Address . And it can be in these IP Build an overlay network between addresses ( Overlay Network ), Through this overlay network , Transfer the packet to the target container intact

  • ETCD And Flannel Provide instructions

    • Storage management Flannel Distributable IP
    • monitor ETCD Each of them Pod The actual address of , And build maintenance in memory Pod
  • Communication in different situations

    • The same Pod Internal communication : The same Pod Share the same network namespace , Share the same Linux agreement
    • Pod1 to Pod2
      • Pod1 And Pod2 Not on the same host , Pod The address is with docker0 In the same network segment , but docker0 Network segment and host network card are two completely different IP Network segment , And different Node Communication between hosts can only be done through the host's physical network card . take Pod Of IP And where Node Of IP Connect , Through this connection let Pod Can access each other
      • Pod1 And Pod2 On the same machine , from Docker0 The bridge forwards the request directly to Pod2 , No need to go through Flannel
    • Pod to Service Network of
      • At present, based on performance considerations , All for iptables Maintain and forward
    • Pod Go to the Internet
      • Pod Send a request to the Internet , Lookup routing table , Forward packets to the host network card , After the host network card completes routing selection , iptables perform Masquerade , Source IP Change to host network card IP , Then send the request to the Internet server
    • Extranet access Pod
      • Service

5、 ... and 、 Resource list

1、 The resource type

  • Namespace level
    • Workload resources ( workload )
      • Pod 、 ReplicaSet 、 Deployment 、 StatefulSet 、 DaemonSet 、 Job 、CronJob ( ReplicationController stay v1.11 The version is obsolete )
    • Service discovery and load balancing resources ( ServiceDiscovery LoadBalance )
      • Service 、 Ingress 、 ...
    • Configuration and storage resources 、
      • Volume( Storage volume ) 、 CSI( Container storage interface , , Can expand a variety of third-party storage volumes )
    • Special types of storage volumes
      • ConfigMap ( When the configuration center comes to use the resource type ) 、 Secret( Save sensitive data ) 、DownwardAPI( Output information from the external environment to the container )
  • Cluster-level resources
    • Namespace 、 Node 、 Role 、 ClusterRole 、 RoleBinding 、 ClusterRoleBinding
  • Metadata resources
    • HPA 、 PodTemplate 、 LimitRange

2、 Resource list file YAML

  • k8s Both resource management and resource object choreography and deployment in a cluster can be implemented through declaration style (YAML) File to solve , In other words, you can edit the resource object operations to YAML Format file , We call this kind of file resource list file , adopt kubectl Command directly uses the resource list file to arrange and deploy a large number of resource objects
  • YAML : It's still a sign language . To emphasize that the language is data centric , Instead of focusing on Markup Language .YAML Is a high readability , Format used to express data sequence

2.1、YAML Grammar introduction

  • Use spaces as indents
  • The number of Spaces indented is not important , As long as the elements of the same level are aligned to the left
  • It is not allowed to use... When indenting a lower version Tab key , Only Spaces are allowed
  • Use # Identification notes , From this character to the end of the line , Will be ignored by the interpreter

2.2、YAML Supported data structures

  • object : Set of key value pairs , Also known as mapping (mapping)/ Hash (hashes) / Dictionaries (dictionary)

    • #  object type : A set of key value pairs for an object , Use the colon structure to indicate 
      name: Steve
      age: 18
      # Yaml  Another way of writing is also allowed , Write all key value pairs as an inline object 
      hash: { name: Steve, age: 18 }
      
  • Array : A set of values in order , Also called sequence (sequence) / list (list)

    • #  An array type : A line at the beginning of a conjunctional line , Make an array 
      animal
      - Cat
      - Dog
      #  Arrays can also be represented in rows 
      animal: [Cat, Dog]
      
  • Composite structure : Objects and arrays can be used in combination , Form a composite structure

    • languages:
      - Ruby
      - Perl
      - Python
      websites:
      YAML: yaml.org
      Ruby: ruby-lang.org
      Python: python.org
      Perl: use.perl.org
      
  • Pure quantity (scalars): A single 、 Nonseparable value

    • #  character string   Boolean value   Integers   Floating point numbers  Null
      #  Time   date 
      #  Values are expressed directly in the form of literal quantities 
      number: 12.30
      #  Boolean value true and false Express 
      isSet: true
      # null use  ~  Express 
      parent: ~
      #  Time Adoption  ISO8601  Format 
      iso8601: 2001-12-14t21:59:43.10-05:00
      #  The date is compound  iso8601  Year of format 、 month 、 Said Monday 
      date: 1976-07-31
      # YAML  Two exclamation marks are allowed , Cast data types 
      e: !!str 123
      f: !!str true
      
  • String considerations

    • #  By default, strings do not use quotation marks 
      str:  This is a line of string 
      #  If the string contains spaces or special characters , It needs to be in quotation marks 
      str: ' Content :  character string '
      #  Both single and double quotation marks can be used , Double quotes do not escape special characters 
      s1: ' Content \n character string '
      s2: " Content \n character string "
      #  If there is a single quotation mark in the single quotation mark , You must use two consecutive single quotation marks to escape 
      str: 'labor''s day'
      #  Strings can be written in multiple lines , Start with the second line , There must be a single space indent . The newline will be converted to   Space 
      str:  This is a paragraph. 
        Multiple lines 
        character string 
      #  Multiline strings can be used | Keep line breaks , You can also use > Fold wrap 
      this: |
      Foo
      Bar
      that: >
      Foo
      Bar
      # +  Represents a wrap at the end of a reserved block of text ,-  Indicates to delete the line break at the end of the string 
      s1: |
       Foo
      s2: |+
       Foo
      s3: |-
       Foo
      

3、 Common field description

  • Properties that must exist

    • Parameter name Field type explain
      version String k8s Of api edition , At present, the basic time is v1, It can be used kubectl api-versions Command query
      kind String finger yaml File defined resource types and roles , such as Pod
      metadata Object Metadata object , Fixed value write metadata
      metadata.name String The name of the metadata object , It's written by us , such as Pod Name
      metadata.namespace String The namespace of the metadata object , By our own definition
      spec Object Define objects in detail , Fixed value write spec
      spce.containers[] list spec List of containers for objects
      spce.containers[].name String Define the name of the container
      spce.containers[].image String The definition of a mirror container
  • Main object

    • Parameter name Field type explain
      spce.containers[].name String Define the name of the container
      spce.containers[].image String The definition of a mirror container
      spce.containers[].imagePullPolicy String The pull strategy of mirror image
      Always: Every time you pull a new image
      Never: Use only local mirrors , Never pull
      IfNotPresent: If it's local, use the local image , If you don't have it, take it , Don't write default Always
      It is recommended to use IfNotPresent, because docker in latest Not a fixed value , Constantly changing
      spce.containers[].command[] list Start command for container , Because it's an array, you can specify multiple , If not specified, use the command in the image packaging
      spce.containers[].args[] list Parameters of the container start command , Because it's an array, you can specify multiple
      spce.containers[].workingDir String Working directory of the container
      spce.containers[].volumeMounts[] list Location of storage volume inside container
      spce.containers[].volumeMounts[].name String The name of the storage volume on which the container is mounted
      spce.containers[].volumeMounts[].mountPath String The storage volume path on which the container is mounted
      spce.containers[].volumeMounts[].readOnly String Container mounted storage volume read / write mode ,true or false, Default true read-only
      spce.containers[].ports[] list List of ports used by the container
      spce.containers[].ports[].name String Specify the port name
      spce.containers[].ports[].containerPort String Specify the port that the container needs to listen on
      spce.containers[].ports[].hostPort String Specify the port number that the host of the container needs to listen to , Default and containerPort identical , Pay attention to the settings hostPort The same host cannot start a virtual copy of the container ( Because the slogan of the host can't be the same , It's going to conflict )
      spce.containers[].ports[].protocol String The protocol of the specified port , Support TCP and UDP, Default TCP
      spce.containers[].env[] list Specifies the list of environment variables to be set before the container runs
      spce.containers[].env[].name String Environment variable name
      spce.containers[].env[].value String Specify the environment variable value
      spce.containers[].resources Object Resource limits and resource request values
      spce.containers[].resources.limits Object Container runtime resource limit ( The maximum resource that can be used to run the container )
      spce.containers[].resources.limits.cpu String CPU The limitation of , Unit is core Count , Will be used for docker run --CPU-shares Parameters
      spce.containers[].resources.limits.memory String Memory limit , Unit is MIB、GIB
      spce.containers[].resources.requests Object Container startup and scheduling constraints ( The minimum resource required to run the container )
      spce.containers[].resources.requests.cpu String CPU The limitation of , Unit is core Count
      spce.containers[].resources.requests.memory String Memory limit , Unit is MIB、GIB
  • Extra parameters

    • Parameter name Field type explain
      spec.restartPolicy String Pod The restart strategy of
      Always:Pod Once it stops running , No matter how the container is terminated ,kubelet Services restart it , Default
      Onfailure: Only Pod Exit with a non-zero exit ,kubelet Will restart the container , The normal end exit code is 0
      Never:Pod After termination ,kubelet Report the exit code to master Won't restart
      spec.nodeSelector Object Definition Node Of label Filter tags , With key:value Format designation
      spec.imagePullSecrets Object Definition pull Used when mirroring secret name , With name:secretkey Format designation
      spec.hostNetwork boolean Define whether to use host network mode , Default false, Set up true Indicates that the host network is used
      Don't use docker bridge , Also set up true You will not be able to start a second copy on the same host
  • version explain

    • #  View the current k8s Supported by version
      kubectl api-versions
      #  View the version supported by a resource   such as Pod
      kubectl explain pod  perhaps  kubectl explain pod.apiVersion( Can be found in FIELDS Select the specific field in the selection field , Detailed view )
      KIND:     Pod
      VERSION:  v1
      
      DESCRIPTION:
           Pod is a collection of containers that can run on a host. This resource is
           created by clients and scheduled onto hosts.
           
      FIELDS:
         apiVersion   <string>
           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
      
         kind <string>
           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
      
         metadata     <Object>
           Standard object's metadata. More info:
           https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
      
         spec <Object>
           Specification of the desired behavior of the pod. More info:
           https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
      
         status       <Object>
           Most recently observed status of the pod. This data may not be up to date.
           Populated by the system. Read-only. More info:
           https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
      

4、 Resource list example

  • apiVersion: v1
    kind: Pod
    metadata:
      name: pod-demo
      #  Namespace   Default default
      namespace: default
      labels:
        app: myapp
    spec:
      containers:
      #  The first container   Pay attention to the same Pod Ports exposed by more than one container in cannot conflict , Because they share networks and storage   For example, both are nginx, It's going to start wrong , Trigger pod The restart strategy of 
      - name: myapp-1
        image: nginx
      #  The second container 
      # - name: myapp-2
      #  image: nginx
    
  • #  Use yaml Start the resource 
    kubectl apply -f yaml file name 
    
    #  see pod Description of  deployment etc. 
    kubectl describe pod( The resource type ) pod-demo( Resource name )
    
    #  see pod Content container log 
    kubectl log pod-demo(pod name ) -c myapp-2( Container name , If Pod There is only one container in , No need to write -c)
    
    #  Delete pod deployment etc. 
    kubectl delete pod( The resource type ) pod-demo( Resource name )
    
    #  Will be resources of yaml The output from 
    kubectl get pod( The resource type ) pod-demo( Resource name ) -o yaml
    
  • [root@k8smaster ~]# kubectl describe pod pod-demo
      ......
      Containers:
        myapp-1:
          Container ID:   docker://5f81ea72fdfa7e720d3aba5e448eb26dc36e0be4763654ceb08eb4be75e6455a
          Image:          nginx
          Image ID:       docker-pullable://nginx@sha256:31de7d2fd0e751685e57339d2b4a4aa175aea922e592d36a7078d72db0a45639
          Port:           <none>
          Host Port:      <none>
          State:          Running
            Started:      Tue, 15 Dec 2020 13:47:41 +0800
          Ready:          True
          Restart Count:  0
          Environment:    <none>
          Mounts:
            /var/run/secrets/kubernetes.io/serviceaccount from default-token-99w8n (ro)
        myapp-2:
          Container ID:   docker://d12c9d0833239a987768e64fe1111fcd8d68036549e9e9a514c0a0dbb5bb4853
          Image:          nginx
          Image ID:       docker-pullable://nginx@sha256:31de7d2fd0e751685e57339d2b4a4aa175aea922e592d36a7078d72db0a45639
          Port:           <none>
          Host Port:      <none>
          State:          Waiting
            Reason:       CrashLoopBackOff
          Last State:     Terminated
            Reason:       Error
            Exit Code:    1
            Started:      Tue, 15 Dec 2020 13:49:28 +0800
            Finished:     Tue, 15 Dec 2020 13:49:31 +0800
          Ready:          False
          Restart Count:  3
          Environment:    <none>
          Mounts:
            /var/run/secrets/kubernetes.io/serviceaccount from default-token-99w8n (ro)
      ......
      
      [root@k8smaster ~]# kubectl get pod
      NAME       READY   STATUS             RESTARTS   AGE
      pod-demo   1/2     CrashLoopBackOff   3          2m52s
    

版权声明
本文为[xiaokantianse]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224152542953O.html

Scroll to Top