Write k8s yaml

Reef 2022-06-24 07:57:14 阅读数:535

writek8syaml


This article refers to the article :Kubernetes series ( Four ): How to write k8s yaml file - - zero - Blog Garden (cnblogs.com)

One 、 summary

K8s in , Support YAML and JSON Two formats to manage resource objects , But generally speaking JSON The format is more for api Message passing between interfaces , and YAML Format is a language that is specifically used to write configuration files , contrast JSON More concise and convenient , therefore , stay K8S It is commonly used in YAML File to manage resource objects

Two 、YAML Document basis

  • YAML The rules of documentation :

    1. Word in file Case sensitive
    2. yaml Indents are used in files to indicate hierarchical relationships , And only use Space
    3. The number of spaces used for indentation is not important , as long as Same level alignment that will do
    4. yaml Use... In the document # To represent a comment
    5. Indent one character after the character , Colon :、 comma ,、 Short cross bar - etc.
    6. --- Indicates the beginning of the file , utilize --- Multiple resources can be written to one yaml In file
  • YAML The structure type of the file :

    (1) Key value pair ——key:value:YAML The basic entry type in the file is Key value pair type , The format is : key : value , Be careful There is a space between the colon and the value

    - for example :
    apiVersion: apps/v1
    kind: Deployment
    # These two are key value pairs , There is a space between 
    - convert to json Format :
    {
    
    "apiVersion": "apps/v1",
    "kind": "Deployment"
    }
    

    (2) list ( Array )——list: The list will list some elements under the list name , In fact, it is an array , List with - start , There can be multiple lists , Note the indentation of each element in the list

    - for example :
    args:
    - "test"
    - "aaaa"
    - "ccc"
    # Note that indents need to be the same 
    - convert to json Format
    {
    
    "args": [
    "test",
    "aaaa",
    "ccc"
    ]
    }
    

    (3) Dictionaries ( Map )——map: The dictionary contains key value pairs 、 list , You can also nest dictionaries

    - for example :
    metadata:
    labels:
    app: test
    name: test
    namespace: test
    # You can nest dictionaries 
    - convert to json Format
    {
    
    "metadata": {
    
    "labels": {
    
    "app": "test"
    },
    "name": "test",
    "namespace": "test"
    }
    }
    
  • From the above structure type, we can see ,YAML Than JSON More concise , Easier to write

3、 ... and 、YAML Use

  • stay K8S in ,Pod It's the smallest unit ,Pod All the information is recorded in one YAML In file
  • Here's the definition PodYAML Some parameters of the file

- Required parameters :

  • One YAML In file , The following parameters must be written , Otherwise, an error will be reported :
Parameters Value type effect
aplVersion character string str Appoint K8S Of API edition , Usually use v1, have access to kubectl api-versions Inquire about Available version , About the version, you can go to k8s Check the official website of
kind character string str Define resource types and roles , for example :Pod、Deployment etc.
metadata object Object Metadata object , There is no need to write other values later , You just need to write metadata: that will do
metadata.name character string str Define the name of the metadata object , Used for naming Pod Name
metadata.namespace character string str Define the namespace of the metadata object , Is used to specify the Pod The namespace of
spec object Object Define objects in detail , No other values need to be written later , You just need to write spec: that will do
spec.containers list list Definition spec List of containers for objects
spec.containers.name character string str Define the name of the container
spec.containers.image character string str Define the image name used by the container
  • That's what happened K8S Write a YAML Necessary parameters of the file

- spec.containers main parameter

  • spec.containers It's a list list, The function is to define the relevant parameters of the container , Here is spec.containers Main parameters of
Parameter name Value type effect
spec.containers.name character string str Used to define the name of the container
spec.containers.image character string str Used to define the image name used by the container
spec.containers.imagePullPolicy character string str Used to define the policy for pulling images , Yes Always( Try to pull the image again every time )Never( Never pull the mirror , Use local mirror )IfNotPresent( If there is a local image, it must be local , No, just pull the image ) Three strategies , The default is Always
spec.containers.command list list Used to specify the container startup command , You can specify multiple , If it is not specified, the startup command used by the image itself is used
spec.containers.args list list Used to specify the container startup command Parameters , You can specify multiple , If it is not specified, the startup command used by the image itself will be used
spec.containers.workingDir character string str Used to specify the working directory of the container , If not specified, the working directory set by the image itself will be used
spec.containers.volumeMounts list list Used to specify the storage volume location inside the container
spec.containers.volumeMounts.name character string str Used to specify the storage volume mounted by the container name
spec.containers.volumeMounts.mountPath character string str Used to specify the storage volume mounted by the container route
spec.containers.volumeMounts.readOnly character string str Used to set the read / write mode of the storage volume path , The value is true perhaps false, The default is read-write mode
spec.containers.ports list list Used to specify the port required by the container , Can write multiple
spec.containers.ports.name character string str Used to specify the name of the port above
spec.containers.ports.containerPort character string str Used to specify the port number that the container needs to listen on
spec.containers.ports.hostPort character string str Used to specify the port number that the host of the container needs to listen to , The default is to follow the above containerPort identical , We need to pay attention to : Set up hostPort The same host of cannot start the same copy of the container , Because the port number of the host cannot be the same , There will be conflicts
spec.containers.ports.protocol character string str Used to specify the port protocol , Support TCP and UDP, The default is TCP
spec.containers.env list list Used to specify the environment variables to be set before the container runs , You can specify multiple
spec.containers.env.name character string str Use to specify the environment variable name
spec.containers.env.value character string str Used to specify the value of the environment variable
spec.containers.resources object Object Values used to specify container resource limits and resource requests
spec.containers.resources.limits object Object Used to specify the allocation and upper limit of container runtime resources
spec.containers.resources.limits.cpu character string str Used to specify the container CPU The limitation of , Unit is core Check the number
spec.containers.resources.limits.memory character string str Is used to specify the mem Memory limit , Unit is MB and GB
spec.containers.resources.requests object Object Used to specify the resource limit when the container is started and scheduled
spec.containers.resources.requests.cpu character string str Used to specify when the container starts CPU Number of available initializations , The unit of quantity is core Check the number
spec.containers.resources.requests.memory character string str Used to specify the number of initialization available when the container is started , The unit of quantity is MB and GB

- spec.volumes main parameter

  • spec.volumes It's a list list , Define parameters for synchronous storage , Here are the main parameters
Parameter name Value type effect
spec.volumes.name character string str Used for definition Pod Shared storage volume name for , With the container definition section spec.containers.volumeMounts.name The value of is the same
spec.volumes.emptyDir object Object Is used to specify the Pod The temporary directory of , Value is an empty object emptyDir:{}
spec.volumes.hostPath object Object Used to specify mount Pod The directory of the host machine where the
spec.volumes.hostPath.path character string str Is used to specify the Pod Host Directory , Will be used in containers mount Mounted Directory
spec.volumes.secret object Object Used to specify that the type is secret The storage volume of ,secret Meaning private 、 Secret means , It's easy to understand , It can store some passwords 、token Or sensitive security files such as secret keys . Mount cluster predefined secret Object to the inside of the container
spec.volumes.configMap object Object Used to specify that the type is configMap The storage volume of , Indicates that the cluster is pre-defined configMap Object to the inside of the container
spec.volumes.livenessProbe object Object Is used to specify the Pod Settings for the content container health check , When the probe fails to respond several times , The system will automatically restart the container
spec.volumes.livenessProbe.exec object Object Is used to specify the Pod Settings for the content container health check , Use exec The way
spec.volumes.livenessProbe.exec.command character string str Is used to specify the exec Command or script needs to be specified after mode , Use this parameter to set
spec.volumes.livenessProbe.httpGet object Object Is used to specify the Pod Settings for the content container health check , Use httpGet The way
spec.volumes.livenessProbe.tcpSocket object Object Is used to specify the Pod Settings for the content container health check , Use tcpSocket The way
spec.volumes.livenessProbe.initialDelaySeconds Numbers num Time setting for manual detection after container startup , Unit is s second
spec.volumes.livenessProbe.timeoutSeconds Numbers num Timeout setting for waiting for response to probe for container health check , Unit is s second , The default is 1s. If the timeout is exceeded, set , The container is considered unhealthy , Will restart the container .
spec.volumes.livenessProbe.periodSeconds Numbers num Set the periodic detection time for the health inspection of the container , Unit is s second , Default 10s Probe once .

- Extra parameter objects

  • Except for the top containers Container settings and volumes Mount settings , There are several other parameters
Parameter name Field type explain
spec.restartPolicy character string str Used for definition Pod The restart strategy of , Optional value is Always(Pod Once terminated ,kubelet Just restart it immediately , For whatever reason )OnFailure( Only Pod In a 0 When the exit code terminates ,kubelet Will restart , If the exit code is 0 That's the normal end , Will not restart ),Never(Pod After termination ,kubelet Will submit the report to master, Won't restart pod) The default value is Always
spec.nodeSelector object Object Used for definition Node Of Label Filter tags , With key:value Format designation
spec.imagePullSecrets object Object Used for definition pull When mirroring, use secret name , With name:secretkey Format designation
spec.hostNetwork Boolean value boolean Used to define whether to use host network mode , The default value is false. Set up true Indicates that the host network is used , Don't use docker bridge , Be careful : Also set up true You will not be able to start a second copy on the same host , In other words, only one host can use the host network pod

Four 、Pod Complete definition file

apiVersion: v1 # Mandatory , Version number , for example v1, Version number must be available kubectl api-versions Query to .
kind: Pod # Mandatory , The type is Pod
metadata: # Mandatory , Metadata 
name: string # Mandatory ,Pod The name of 
namespace: string # Mandatory ,Pod The namespace to which it belongs , The default is "default", This is defined as string
labels: # Custom tag 
- name: string # Custom tag name 
annotations: # Custom comment list 
- name: string
spec: # Mandatory ,Pod Detailed definition of container in 
containers: # Mandatory ,Pod List of containers in 
- name: string # Mandatory , Container name , To comply with RFC 1035 standard 
image: string # Mandatory , Image name of the container 
imagePullPolicy: [ Always|Never|IfNotPresent ] # The strategy of getting images , Three strategies , The above parameters are described in detail 
command: [string] # Start command list of container , If not specified , Use the startup command used when packaging 
args: [string] # Start command parameter list of container 
workingDir: string # Working directory of the container 
volumeMounts: # Storage volume configuration mounted inside the container 
- name: string # quote pod The name of the defined shared storage volume , need volumes[] The volume name of the partial definition 
mountPath: string # The storage volume is in the container mount The absolute path of , Should be less than 512 character 
readOnly: boolean # Is it read-only mode 
ports: # List of port library numbers to be exposed 
- name: string # The name of the port 
containerPort: int # The port number the container needs to listen on 
hostPort: int # The port number that the host of the container needs to listen to , Default and Container identical 
protocol: string # Port agreement , Support TCP and UDP, Default TCP
env: # List of environment variables to be set before the container runs 
- name: string # Environment variable name 
value: string # The value of the environment variable 
resources: # Resource limits and request settings 
limits: # Resource limit settings 
cpu: string #Cpu The limitation of , Unit is core Count , Will be used for docker run --cpu-shares Parameters 
memory: string # Memory limit , The unit can be Mib/Gib, Will be used for docker run --memory Parameters 
requests: # Settings for resource requests 
cpu: string #Cpu request , Initial available number of container starts 
memory: string # Memory request , Initial available number of container starts 
livenessProbe: # Yes Pod Setting of health examination for each container inside , The container will restart automatically after several times of no response , The inspection methods are exec、httpGet and tcpSocket, Just set one of these methods for a container 
exec: # Yes Pod The in container inspection mode is set to exec The way 
command: [string] #exec A command or script that needs to be formulated 
httpGet: # Yes Pod The internal container health check method is set to HttpGet, Need to make Path、port
path: string
port: number
host: string
scheme: string
HttpHeaders:
- name: string
value: string
tcpSocket: # Yes Pod Internal container health check mode is set to tcpSocket The way 
port: number
initialDelaySeconds: 0 # Time of the first detection after the start of the container , The unit is in seconds 
timeoutSeconds: 0 # Timeout for container health probe to wait for response , Unit second , Default 1 second 
periodSeconds: 0 # Set the regular detection time for container monitoring and inspection , Unit second , Default 10 Seconds at a time 
successThreshold: 0
failureThreshold: 0
securityContext:
privileged: false
restartPolicy: [Always | Never | OnFailure] #Pod The restart strategy of , Three models , The above parameters are described in detail 
nodeSelector: obeject # Set up NodeSelector It means that you should Pod Schedule to include this label Of node On , With key:value The format of 
imagePullSecrets: #Pull Used when mirroring secret name , With key:secretkey Format designation 
- name: string
hostNetwork: false # Whether to use the host network mode , The default is false, If set to true, Indicates that the host network is used 
volumes: # In the pod List of shared storage volumes defined on 
- name: string # Shared storage volume name (volumes There are many types )
emptyDir: {
} # The type is emtyDir The storage volume of , And Pod A temporary directory in the same lifecycle . Null value 
hostPath: string # The type is hostPath The storage volume of , Means mount Pod Directory of host 
path: string #Pod Directory of host , Will be used in the same period mount The catalog of 
secret: # The type is secret The storage volume of , Mount the cluster with the defined secre Object to the inside of the container 
scretname: string
items:
- key: string
path: string
configMap: # The type is configMap The storage volume of , Mount predefined configMap Object to the inside of the container 
name: string
items:
- key: string
path: string

5、 ... and 、Deployment Complete definition file

apiVersion: apps/v1
kind: Deployment
metadata:
spec:
minReadySeconds: <integer> # Set up pod The minimum number of seconds to be ready 
paused: <boolean> # Indicates that the deployment has been suspended and deploy The controller does not process the deployment 
progressDeadlineSeconds: <integer>
strategy: <Object> # Put the existing pod Replace with new pod Deployment strategy 
rollingUpdate: <Object> # Scroll through configuration parameters , Only if the type is RollingUpdate
maxSurge: <string> # The biggest cost of rolling update process is pod Number , It can be a number , It can also be a percentage 
maxUnavailable: <string> #
type: <string> # Deployment type ,Recreate,RollingUpdate
replicas: <integer> #pods Number of copies of 
selector: <Object> #pod tag chooser , matching pod label , By default pods The label of 
matchLabels: <map[string]string>
key1: value1
key2: value2
matchExpressions: <[]Object>
operator: <string> -required- # Set the relationship between a label key and a set of values ,In, NotIn, Exists and DoesNotExist
key: <string> -required-
values: <[]string>
revisionHistoryLimit: <integer> # Set the number of historical versions to keep , The default is 10
rollbackTo: <Object>
revision: <integer> # Set the version of the rollback , Set to 0 Then roll back to the previous version 
template: <Object> -required-
metadata:
spec:
containers: <[]Object> # Container configuration 
- name: <string> -required- # Container name 、DNS_LABEL
image: <string> # Mirror image 
imagePullPolicy: <string> # Mirror pull strategy ,Always、Never、IfNotPresent
ports: <[]Object>
- name: # Define the port name 
containerPort: # Exposed port of container 
protocol: TCP # or UDP
volumeMounts: <[]Object>
- name: <string> -required- # Set the volume name 
mountPath: <string> -required- # Set the path in the container to be mounted 
readOnly: <boolean> # Set whether it is read-only or not 
livenessProbe: <Object> # Ready to detect 
exec:
command: <[]string>
httpGet:
port: <string> -required-
path: <string>
host: <string>
httpHeaders: <[]Object>
name: <string> -required-
value: <string> -required-
scheme: <string>
initialDelaySeconds: <integer> # Set how many seconds to start detection 
failureThreshold: <integer> # Set the number of consecutive failed detections , Mark as failure , Three times by default 
successThreshold: <integer> # Set the minimum number of consecutive successful probes after failure , The default is 1
timeoutSeconds: <integer> # Set the number of seconds for the probe timeout , Default 1s
periodSeconds: <integer> # Set the frequency to perform the probe ( In seconds ), Default 1s
tcpSocket: <Object> #TCPSocket The designation involves TCP Port operation 
port: <string> -required- # Exposed port of container 
host: <string> # Default pod Of IP
readinessProbe: <Object> # Same as livenessProbe
resources: <Object> # Resource allocation 
requests: <map[string]string> # Minimum resource allocation 
memory: "1024Mi"
cpu: "500m" #500m representative 0.5CPU
limits: <map[string]string> # Maximum resource allocation 
memory:
cpu:
volumes: <[]Object> # Data volume configuration 
- name: <string> -required- # Set the volume name , And volumeMounts The name corresponds to 
hostPath: <Object> # Set the mount host path 
path: <string> -required-
type: <string> # type :DirectoryOrCreate、Directory、FileOrCreate、File、Socket、CharDevice、BlockDevice
- name: nfs
nfs: <Object> # Set up NFS The server 
server: <string> -required- # Set up NFS Server address 
path: <string> -required- # Set up NFS Server path 
readOnly: <boolean> # Set whether it is read-only or not 
- name: configmap
configMap:
name: <string> #configmap name 
defaultMode: <integer> # permissions 0~0777, Default 0664
optional: <boolean> # Specifies whether... Must be defined configmap Or its keys
items: <[]Object>
- key: <string> -required-
path: <string> -required-
mode: <integer>
restartPolicy: <string> # Restart strategy ,Always、OnFailure、Never
nodeName: <string>
nodeSelector: <map[string]string>
imagePullSecrets: <[]Object>
hostname: <string>
hostPID: <boolean>
status: <Object>
copyright:author[Reef],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/202206240400115956.html