Detailed Kubernetes (k8s) YAML file

[Directory]

1. Introduction to yaml file
2. Common yaml Syntax
3. port Details
4. A simple example of yarml
V. Label and Selector
6. Differences between kubectl creation or kubectl replace ment

1. Introduction to yaml file

Kubernetes only supports the creation of resource objects in YAML and JSON formats, which are used for message delivery between interfaces and are suitable for development. The YAML format is used for configuration and management and for cloud platform management. YAML is a concise, non-markup language.

1) The grammar rules of yaml:

  • Case Sensitive
  • Use indentation to represent hierarchical relationships
  • Tal key is not allowed for indentation, only spaces are allowed
  • The number of indented spaces is not important as long as the elements of the same level are aligned to the left
  • "#" denotes a comment and is ignored by the parser from this character to the end of the line
  • Note: - - - Optional separator, used when multiple structures need to be defined in one file

2) In Kubernetes, you only need to know two types of structures:

  • Lists
  • Maps

2.1)YAML Maps
Map, as its name implies, refers to a dictionary, a key-value pair of information for a Key:Value. For example:

---
apiVersion: v1
kind: Pod

The above indicates that there are two keys, apiVersion and type, corresponding to v1 and Pod, respectively.

The value of a Maps can correspond to either a string or a Maps. For example:

---
apiVersion: v1
kind: Pod
metadata:
  name: kube100-site
  labels:
    app: web

Note: In the YAML file above, the metadata KEY corresponds to a Maps, while the nested labels KEY corresponds to a Map. Multilayer nesting is possible in real use.

The YAML processor knows the association between the contents based on line indentation. In the example above, two spaces are used for indentation, but the amount of data for the spaces is not important, it requires at least one space and all indentations are consistent. For example, name and labels are at the same indentation level, so the YAML processor knows they belong to the same map; It knows that app is the value of lables because app has a larger indentation.

2.2)YAML Lists
List is a list, or simply an array, for example:

args
 -beijing
 -shanghai
 -shenzhen
 -guangzhou

You can specify any number of items in the list, with each item defined starting with a dash (-) and indented from the parent element.

Of course, the subitems of Lists can also be Maps, and the subitems of Maps can also be Lists, for example:

---
apiVersion: v1
kind: Pod
metadata:
  name: kube100-site
  labels:
    app: web
spec:
  containers:
    - name: front-end
      image: nginx
      ports:
        - containerPort: 80
    - name: flaskapp-demo
      image: jcdemo/flaskapp
      ports: 8080

As shown in the above file, a List object for containers is defined. Each subitem consists of name, image, ports, and each ports has a Map whose KEY is containerPort.

2. Common yaml Syntax

1)apiVersion
View all currently available API versions

$ kubectl api-versions

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-9B31EtLI-16310283805). ( https://img- Bold style blog.csdnimg.cn/f1facfa023cd430ebc16c4279b4a3abf.png?X-oss-process=image/watermark, type_ZHJvaWRz5zmFsbGJhY2s, shadow_50, text_Q1NETiBA5a-S5rGf5a2k5b2xMDA3, size_15, FFFF, t_70, g_se, x_16)]

Prior to version 1.6 apiVsersion:extensions/v1beta1
Between version 1.6 and 1.9: apps/v1beta1
After version 1.9: apps/v1

Common apiversion s

Just remember that six commonly used apiversion s are usually enough.

  • The stable version of the v1: Kubernetes API contains many core objects: pod, service, and so on.
  • apps/v1: An api combination that contains some common application layers, such as Deployments, RollingUpdates, and ReplicaSets.
  • batch/v1: Contains objects related to batch and similar jobs such as job, cronjob.
  • autoscaling/v1: Allows containers to be automatically adjusted based on different resource usage metrics.
  • networking.k8s.io/v1: For Ingress.
  • rbac.authorization.k8s.io/v1: For RBAC.

Below is the official link to the original text. Interested students can see that the page is in a language of choice, but there is a problem with Chinese translation. It is recommended that you look at it in Chinese and English. https://kubernetes.io/docs/reference/using-api/

2)kind

kind specifies the type of this resource object, such as pod, deployment, statefulset, job, cronjob

3)metadata

A common configuration item for metadata is name,namespace, which configures the name it displays and the namespace it belongs to.

4)spec

The configuration item of a nested dictionary and list is also the main configuration item, which supports many subitems. Depending on the resource object, the subitems will have different configurations.

For example, the spec configuration for a pod:

apiVersion: v1 #Required, version number, e.g. v1
kind: Pod #Required, Pod 
metadata: #Required, Metadata 
  name: nginx #Required, Pod name 
  labels: #Custom Label 
     app: nginx #Custom Label Name 
spec: #Required, detailed definition of container in Pod 
     containers: #Required, list of containers in a Pod, there will be multiple containers in a pod 
        - name: nginx #Required, container name 
          image: nginx #Required, mirror name of container 
          imagePullPolicy: IfNotPresent # [Always | Never | IfNotPresent] #The strategy for getting mirrors Alawys indicates downloading mirrors IfnotPresent indicates preferring local mirrors, otherwise downloading mirrors, Nerver indicates using only local mirrors 
          ports: #List of port library numbers to expose 
          - containerPort: 80 #Port number the container needs to listen on 
     restartPolicy: Always # [Always | Never | OnFailure]#Pod's restart policy, Always indicates that once the run is terminated in any way, kubelet will restart, OnFailure indicates that only Pod will restart if it exits with a non-zero exit code, and Nerver indicates that the Pod will not be restarted again 

Configuration of spec for a service:

apiVersion: v1
kind: Service
metadata:
  name: service-hello
  labels:
  name: service-hello
spec:
  type: NodePort      #This means NodePort type, plus ingress,LoadBalancer
  ports:
  - port: 80          #The port here corresponds to the cluster IP (port of IP in kubectl describe service-hello), where curl 10.98.166.242:80 can access published application services on all machines in the cluster.
    targetPort: 8080  #The port must correspond to the port exposed by the container. The port exposed by nodejs is 8081, so it should also be 8081 here
    protocol: TCP
    nodePort: 31111   # All nodes will open this port 30000--32767, which is for external calls.
  selector:
    run: hello         #The selector here must select the label of the container. It was wrong to write name:kube-node before.

Here, nginx is mapped to the external network, and the access address is native ip:31111

3. port Details

  • Port:port is the port within the k8s cluster to access a service, that is, a service can be accessed through the cluster IP: port
  • NodePort:nodePort is a port for external access to a service in the k8s cluster and can access a service from outside through nodeIP:nodePort.
  • TargetPort:targetPort is the port of the pod. Traffic from the ports and nodePort flows through kube-proxy to the targetPort of the back-end pod and finally into the container.
  • ContainerPort: ContainerPort is the port of the container inside the pod, and targetPort maps to containerPort.

4. A simple example of yaml

Here's an example of a description of three resources: deployment, pod, service

1)deployment

apiVersion: apps/v1   # Versions prior to 1.9.0 used apps/v1beta2, which can be viewed by the command kubectl api-versions
kind: Deployment    #Specify roles/types to create resources
metadata:    #Metadata/Properties of Resources
  name: nginx-deployment    #The name of the resource, which must be unique within the same namespace
spec:
  replicas: 2    #Number of copies 2
  selector:      #Define Label Selector
    matchLabels:
      app: web-server
  template:      #Definition of Pod here
    metadata:
      labels:    #Pod's label
        app: web-server
    spec:        # Specify the content of this resource  
      containers:  
      - name: nginx      #Name of container  
        image: nginx:1.12.1  #The mirror address of the container    
        ports:  
        - containerPort: 80  #Port outside container

Create deployment resource by executing the following command

$ kubectl create -f nginx.yaml

2)pod

apiVersion: v1
kind: Pod  
metadata:  
  name: pod-redis
  labels:
    name: redis
spec: 
  containers:
  - name: pod-redis
    image: docker.io/redis  
    ports:
    - containerPort: 80 #Port outside container

Create a pod resource by executing the following command

$ kubectl create -f pod-redis.yaml

3)service

apiVersion: v1  
kind: Service  # Indicates that the resource type is service
metadata:  
  name: httpd-svc # The name of the service is httpd-svc
  labels:  
    name: httpd-svc 
spec:  
  ports:  # Map service 8080 port to pod's 80 port, using TCP protocol
  - port: 8080
    targetPort: 80  
    protocol: TCP  
  selector:  
    run: httpd # Indicates which label's pod is the back end of the service

Create a service resource by executing the following command

$ kubectl create -f httpd-svc.yaml

V. Label and Selector

1)Label

Label is another core concept in the Kubernetes series. Is a set of key/value pairs bound to the K8s resource object. The labels property key of the same object must be unique. Labels can be attached to various resource objects, such as Node,Pod,Service,RC, and so on.

By bundling one or more unused label s with a specified resource object, multidimensional resource grouping management functions can be implemented to facilitate flexible and convenient resource allocation, scheduling, configuration, deployment and other management work.

Examples are as follows:

  • Version label:'release':'stable','release':'canary'...
  • Environment tag: "environment": "dev", "environment": "production"
  • Architecture tags:'tier':'frontend','tier':'backend','tier':'middleware'
  • Partition label: "partition": "customerA", "partition": "customerB"...
  • Quality control label:'track':'daily','track':'weekly'

2)Selector

Label selector is the core grouping mechanism of Kubernetes, through which the label selector client/user can identify a group of resource objects with common characteristics or attributes. The od that matches this tag will be the backend of this Service.

apiVersion: v1
kind: Service
metadata:
  name: hello
  labels:
    app: hello
spec:
  ports:
  - port: 80
    targetPort: 80
  selector:
    app: hello

6. Differences between kubectl creation or kubectl replace ment

Both kubectl create-f and kubectl replace-f can create resources, but what are the differences? Please elaborate below.

kubectl create:

  • The kubectl create command creates a new resource. Therefore, if you run the command again, an error will be thrown because the resource name should be unique in the namespace.

kubectl apply:

  • The kubectl apply command applies the configuration to the resource. If the resource is not there, it will be created. The kubectl apply command can be run multiple times because it only applies the configuration shown below. In this case, the configuration has not changed. So the pod hasn't changed.
  • Simply put, if you run operations on a single file to create resources, create and apply are basically the same. However, apply allows you to create and patch multiple files in a directory at the same time.

Keywords: Docker Kubernetes

Added by mithril on Sun, 21 Nov 2021 11:11:23 +0200