linux12k8s -- > 04 resource management and detailed explanation of YAML files

Resource management and YAML files

1, Introduction to resource management

In kubernetes, all contents are abstracted as resources. Users need to manage kubernetes by operating resources.

Kubernetes is essentially a cluster system. Users can deploy various services in the cluster. The so-called deployment service actually means running containers in the kubernetes cluster and running the specified programs in the containers.

The smallest management unit of kubernetes is a pod rather than a container, so the container can only be placed in the pod. Generally, kubernetes does not directly manage the pod, but manages the pod through the pod controller.

After the Pod can provide services, you should consider how to access the services in the Pod. kubernetes provides Service resources to realize this function.

Of course, kubernetes also provides various storage systems if the data of programs in Pod needs to be persistent.

The core of learning kubernetes is to learn how to operate Pod, Pod controller, Service, storage and other resources on the cluster

2, YAML file details

1. YAML file overview

k8s In the cluster, both resource management and resource object arrangement and deployment can be realized through declaration style( YAML)File, that is, you can edit the operation of resource objects to YAML In the format file, we call this file the resource list file kubectl Command directly uses the resource manifest file to arrange and deploy a large number of resource objects.

2. YAML file writing format

1. YAML introduction

1. Resource manifest file

2. Resource arrangement

YAML : It is still a markup language. To emphasize that the language is data centric rather than markup language focused.
YAML Is a highly readable format used to express data sequences.
2. YAML basic syntax
# 1. The number of indented spaces is not important, as long as the elements of the same level are aligned to the left
# 2. The Tab key is not allowed when indenting in lower versions, and only spaces are allowed
# 3, use#The identifier comment, from this character to the end of the line, will be ignored by the interpreter
# 4. Use --- indicates the beginning of a new yaml file
# 5. Case sensitive

3. YAML composition

1. Controller definition

2. Controlled object

apiVersion: v1  #Required. Specifies the version number of the API deployed by K8s
kind:Pod   #Required, resource type Pod
metadata: # Required to record the metadata of the deployed application
  name: nginx # Required, Pod name conforming to RFC 1035 specification
  namespace: web-testing # Optional. default is not specified, and the namespace of Pod is not specified
  labels: # Optional, label Selector, generally used for Selector
    - app: nginx
  annotations: # Optional, Note List
    - app: nginx
spec: # Required to deploy container details
  containers: # Required, container list


1. YAML supports the following data types:
  • Scalar: a single, non separable value
  • Object: a collection of key value pairs, also known as mapping / hash / dictionary
  • Array: a set of values arranged in order, also known as sequence / list
# Scalar refers to a simple value, such as string, Boolean, integer, floating point number, Null, time and date
# 1 boolean type
c1: true (perhaps True)
# 2 integer
c2: 234
# 3 floating point
c3: 3.14
# 4 null type 
c4: ~  # Use ~ for null
# 5 date type
c5: 2021-08-02    # The date must be in ISO 8601 format, i.e. yyyy mm DD
# 6 time type
c6: 2021-08-02T15:02:31+08:00  # The time is in ISO 8601 format, the T connection is used between the time and date, and the last + is used to represent the time zone
# 7 string type
c7: heima     # It is simple to write the value directly. If there are special characters in the middle of the string, it must be wrapped in double quotation marks or single quotation marks 
c8: line1
    line2     # If there are too many strings, they can be split into multiple lines, and each line will be converted into a space
# object
# Form I (recommended):
heima:
  age: 15
  address: Beijing
# Form 2 (understanding):
heima: {age: 15,address: Beijing}
# array
# Form I (recommended):
address:
  - Shunyi
  - Sunrise 
# Form 2 (understanding):
address: [Shunyi,Changping]

2. Tip:
1 write yaml Remember : Add a space after it

2 If necessary, add multiple segments yaml The configuration is placed in a file and used in the middle`---`separate

3 Here is a yaml turn json The website can be verified through it yaml Is it written correctly
#  https://www.json2yaml.com/convert-yaml-to-json

4. yaml detailed explanation

apiVersion: v1  #Required. Specifies the version number of the API deployed by K8s
kind:Pod   #Required, resource type Pod
metadata: # Required to record the metadata of the deployed application
  name: nginx # Required, Pod name conforming to RFC 1035 specification
  namespace: web-testing # Optional. default is not specified, and the namespace of Pod is not specified
  labels: # Optional, label Selector, generally used for Selector
    - app: nginx
  annotations: # Optional, Note List
    - app: nginx
spec: # Required to deploy container details
  containers: # Required, container list
  - name: nginx # Required, container name conforming to RFC 1035
    image: nginx:v1 # Required, the address of the image used by the container
    imagePullPolicy: Always # Optional, image pull strategy
    workingDir: /usr/share/nginx/html # Optional, the working directory of the container
    volumeMounts: # Optional, storage volume configuration
    - name: webroot # Storage volume name
      mountPath: /usr/share/nginx/html # Mount directory
      readOnly: true # read-only
    ports: # Optional, the container needs to expose a list of port numbers
    - name: http # Port name
      containerPort: 80 # Port number
      protocol: TCP # Port protocol, default TCP
    env: # Optional, environment variable configuration
    - name: TZ # Variable name
      value: Asia/Shanghai
    - name: LANG
      value: en_US.utf8
    resources: # Optional, resource limit and resource request limit
      limits: # Maximum limit setting
        cpu: 1000m
        memory: 1024MiB
      requests: # Resources required to start
        cpu: 100m
        memory: 512MiB
     readinessProbe: # Optional, container status check
       httpGet: # Detection mode
         path: / # Check path
         port: 80 # Monitoring port
       timeoutSeconds: 2 # Timeout
       initialDelaySeconds: 60 # Initialization time
     livenessProbe: # Optional, monitor status check
       exec: # Detection mode
         command:
         - cat
         - /health
       httpGet: # Detection mode
         path: /_health
         port: 8080
         httpHeaders:
         - name: end-user
           value: jason
        tcpSocket: # Detection mode
          port: 80
        initialDelaySeconds: 60 # Initialization time
        timeoutSeconds: 2 # Timeout
        periodSeconds: 5 # Detection interval
        successThreshold: 2 # 2 successful checks indicate readiness
        failureThreshold: 1 # Detection failed once, indicating that it is not ready
      securityContext: # Optional, limit the untrusted behavior of the container
        provoleged: false
     restartPolicy: Always # Optional. The default is Always
     nodeSelector: # Optional, specify the Node
       region: subnet7
     imagePullSecrets: # Optional. Pull the secret used by the image
     - name: default-dockercfg-86258
     hostNetwork: false # Optional, whether it is host mode. If yes, it will occupy the host port
     volumes: # Shared storage volume list
     - name: webroot # Name, corresponding to the above
       emptyDir: {} # Shared volume type, empty
       hostPath: # Shared volume type, native directory
         path: /etc/hosts
       secret: # Shared volume type, secret mode, generally used for password
         secretName: default-token-tf2jp # name
         defaultMode: 420 # jurisdiction
         configMap: # Generally used for configuration files
         name: nginx-conf
         defaultMode: 420
         
[root@k8s-m-01 ~]# kubectl explain pod.spec  #View parameters
 string : Follow string
Object : 
[]Object : 
	- name

5. Write yaml files quickly

Method 1: use kubectl create command to generate yaml file

Method 2: use kubectl get command to export yaml file

ate Command generation yaml file

# 1. Generate yaml file
[root@k8s-m-01 ~]# Kubectl create deployment web -- Image = nginx - O yaml -- dry run (but not executed)
W0801 20:45:16.340376   74086 helpers.go:557] --dry-run is deprecated and can be replaced with --dry-run=client.
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: web
  name: web
spec:
  replicas: 1
  selector:
    matchLabels:
      app: web
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: web
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
status: {}
Parameters:
--dry-run  # Do not execute

 Mode 2: use kubectl get Command Guide yaml file
 [root@k8s-m-01 ~]# kubectl get deploy flannel -o=yaml --export > flannel1.yaml

4, Resource management mode

  • 1. Imperative object management: directly use commands to operate kubernetes resources

    kubectl run nginx-pod --image=nginx --port=80
    
  • 2. Imperative object configuration: operate kubernetes resources through command configuration and configuration files

    kubectl create/patch -f nginx-pod.yaml
    
  • 3. Declarative object configuration: operate kubernetes resources through the apply command and configuration file

    kubectl apply -f nginx-pod.yaml  # Used to create and update resources
    
typeOperation objectApplicable environmentadvantageshortcoming
Imperative object managementobjecttestsimpleOnly active objects can be operated, and cannot be audited or tracked
Imperative object configurationfiledevelopmentCan audit and trackWhen the project is large, there are many configuration files and the operation is troublesome
Declarative object configurationcataloguedevelopmentSupport directory operationDifficult to debug under unexpected circumstances

1. Imperative object management

1. kubectl command

kubectl is the command line tool of kubernetes cluster. It can manage the cluster itself and install and deploy container applications on the cluster.

The syntax of the kubectl command is as follows:

kubectl [command] [type] [name] [flags]

comand: Specifies the operations to be performed on the resource, such as create, get, and delete

Type: Specifies the resource type, such as deployment, pod, and service

Name: Specifies the name of the resource. The name is case sensitive

flags: specify additional optional parameters

#  1. View all pod s
[root@k8s-m-01 ~]# kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-pcqrj   1/1     Running   2          11h

#  2. View a pod
[root@k8s-m-01 ~]# kubectl get pod nginx-6799fc88d8-pcqrj 
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-pcqrj   1/1     Running   2          11h

# 3. View a pod and display the results in yaml format
[root@k8s-m-01 ~]# kubectl get pod nginx-6799fc88d8-pcqrj -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP            NODE       NOMINATED NODE   READINESS GATES
nginx-6799fc88d8-pcqrj   1/1     Running   2          11h   10.244.1.12   k8s-n-01   <none>           <none>
# 4. yaml language display
[root@k8s-m-01 ~]#   kubectl get pod pod_name -o yaml
2. Resource type

All contents in kubernetes are abstracted as resources, which can be viewed through the following command:

kubectl api-resources

Frequently used resources include the following:

Resource classificationResource nameabbreviationResource role
Cluster level resourcesnodesnoCluster components
namespacesnsIsolate Pod
pod resourcespodspoLoading container
pod resource controllerreplicationcontrollersrcControl pod resources
replicasetsrsControl pod resources
deploymentsdeployControl pod resources
daemonsetsdsControl pod resources
jobsControl pod resources
cronjobscjControl pod resources
horizontalpodautoscalershpaControl pod resources
statefulsetsstsControl pod resources
Service discovery resourcesservicessvcUnified pod external interface
ingressingUnified pod external interface
Storage resourcesvolumeattachmentsstorage
persistentvolumespvstorage
persistentvolumeclaimspvcstorage
Configure resourcesconfigmapscmto configure
secretsto configure

operation

kubernetes allows multiple operations on resources. You can view detailed operation commands through – help

kubectl --help

Frequently used operations include the following:

Command classificationcommandtranslateCommand function
Basic commandcreateestablishCreate a resource
editeditEdit a resource
getobtainGet a resource
patchto updateUpdate a resource
deletedeleteDelete a resource
explainexplainShow resource documents
Operation and commissioningrunfunctionRun a specified mirror in the cluster
exposeexposeExposed resource is Service
describedescribeDisplay resource internal information
logsjournalOutput container log in pod
attachTwiningEnter the container in operation
execimplementExecute a command in the container
cpcopyCopy files inside and outside the Pod
rolloutFirst showManage publishing of resources
scalescaleNumber of expansion (contraction) Pod
autoscaleAutomatic adjustmentAutomatically adjust the number of pods
Advanced commandapplyrcConfigure resources through files
labellabelUpdate labels on resources
Other commandscluster-infoCluster informationDisplay cluster information
versioneditionDisplays the current Server and Client versions

The following is a simple demonstration of how to use the following commands by creating and deleting a namespace / pod:

# 1. Create a namespace
[root@k8s-m-01 ~]# kubectl create namespace dev
namespace/dev created

# 2. Get namespace
[root@k8s-m-01 ~]# kubectl get namespaces (abbreviation ns)
NAME                   STATUS   AGE
default                Active   3d8h
dev                    Active   6s
kube-node-lease        Active   3d8h
kube-public            Active   3d8h
kube-system            Active   3d8h
kubernetes-dashboard   Active   23h

# 3. Create and run an nginx Pod in this namespace
[root@k8s-m-01 ~]# kubectl run pod --image=nginx -n dev
pod/pod created

# 4. View the newly created pod
[root@k8s-m-01 ~]# kubectl get pod -n dev
NAME   READY   STATUS    RESTARTS   AGE
pod    1/1     Running   0          57s
# 5. View pod details
[root@k8s-m-01 ~]# kubectl describe pods -n dev
Name:         pod
Namespace:    dev
Priority:     0
Node:         k8s-n-02/192.168.15.113
Start Time:   Mon, 02 Aug 2021 23:45:41 +0800
Labels:       run=pod
Annotations:  <none>
Status:       Running
IP:           10.244.2.7
IPs:
  IP:  10.244.2.7
Containers
# 6. Delete the specified pod
[root@master ~]# kubectl delete pod pod 
pod "pod" deleted

# 7. Deletes the specified namespace
[root@master ~]# kubectl delete ns dev
namespace "dev" deleted

2. Imperative object configuration

Imperative object configuration is to use commands to operate kubernetes resources together with configuration files.

1) Create an nginxpod Yaml, as follows
[root@k8s-m-01 ~]# vim nginxpod.yaml 
apiVersion: v1
kind: Namespace
metadata:
  name: dev
---
apiVersion: v1
kind: Pod
metadata:
  name: nginxpod
  namespace: dev
spec:
  containers:
  - name: nginx-containers
    image: nginx:latest
2) Execute the create command to create resources:
[root@k8s-m-01 ~]# kubectl create -f nginxpod.yaml 
namespace/dev created
pod/nginxpod created

At this time, it is found that two resource objects are created, namely namespace and pod

3) Execute the get command to view resources:
[root@k8s-m-01 ~]# kubectl get -f nginxpod.yaml 
NAME            STATUS   AGE
namespace/dev   Active   39s

NAME           READY   STATUS    RESTARTS   AGE
pod/nginxpod   1/1     Running   0          39s

The information of the two resource objects is displayed

4) Execute the delete command to delete resources:
[root@k8s-m-01 ~]# kubectl delete -f nginxpod.yaml
namespace "dev" deleted
pod "nginxpod" deleted

At this time, two resource objects are found to be deleted

summary:
    To operate resources in the way of command object configuration, you can simply think of: command  +  yaml Configuration file (which contains various parameters required by the command)

3. Declarative object configuration

Declarative object configuration is similar to imperative object configuration, but it has only one command, apply.

# First, execute the kubectl apply -f yaml file once and find that the resource is created
[root@k8s-m-01 ~]#  kubectl apply -f nginxpod.yaml
namespace/dev created
pod/nginxpod created

# Execute the kubectl apply -f yaml file again and find that the resource has not changed
[root@k8s-m-01 ~]#  kubectl apply -f nginxpod.yaml
namespace/dev unchanged
pod/nginxpod unchanged

4. Summary

# Summary:
    In fact, declarative object configuration is to use apply Describe the final state of a resource (in yaml (status defined in)
    use apply Operational resources:
        If the resource does not exist, it is created, which is equivalent to kubectl create
        If the resource already exists, it is updated, which is equivalent to kubectl patch

Extension: can kubectl run on node nodes?

kubectl needs to be configured to run. Its configuration file is $home / kube, if you want to run this command on the node node, you need to Copy the kube file to the node node, that is, perform the following operations on the master node:

scp  -r  HOME/.kube   n1: HOME/

Usage recommendation: how to use the three methods?

# 1. Create / update resources 
Use declarative object configuration kubectl apply -f XXX.yaml

# 2. Delete resource use command object configuration 
kubectl delete -f XXX.yaml

# 3. Query resources using imperative object management 
kubectl get(describe) Resource name

Keywords: Kubernetes

Added by fotobleu on Mon, 03 Jan 2022 08:38:36 +0200