当前位置:网站首页>Kubernetes - yaml file interpretation
Kubernetes - yaml file interpretation
2022-07-03 15:10:00 【Fruit brother】
YAML
k8s Multiple are used in *.yaml file , So the format and meaning of these documents 、 How does grammar work ?
One 、YAML Introduce :
1、 brief introduction :
YAML Language ( pronunciation /ˈjæməl/ ) The design goal of , It is convenient for human beings to read and write . It is essentially a universal data serialization format .YAML Also known as json Superset , Compared with json More convenient
2、 grammar :
Case sensitive
Use indentation to indicate hierarchy
Indentation is not allowed Tab key , Only Spaces are allowed .
The number of Spaces indented is not important , As long as the elements of the same level are aligned to the left
# Notation , From the character to the end of the line
3、 Supported data structures
- object : Set of key value pairs , Also known as mapping (mapping)/ Hash (hashes) / Dictionaries (dictionary)
- Array : A set of values in order , Also called sequence (sequence) / list (list)
- Pure quantity (scalars): A single 、 Nonseparable value , The types of scenes are as follows :
- character string
- Boolean value
- Integers
- Floating point numbers
- Null
- Time
- date
k8s(Kubernetes) in Pod、Deployment、ReplicaSet、Service The relationship between them is as follows :
- Pod: To manage containers , Every Pod Can contain one or more closely related containers
- ReplicaSet: yes rc Upgraded version , Also to manage pod,Kubernetes Officials strongly recommend avoiding direct use of ReplicaSet, And it should go through Deployment To create RS and Pod. because ReplicaSet yes ReplicationController A substitute for , So the usage is basically the same , The only difference is ReplicaSet Support for aggregate selector.
- Deployment: More convenient management Pod and Replica Set, Provide release, update, maintenance, monitoring and other functions
- Service: On the basis of this whole set, it provides stable services to the outside
1、Deployment The configuration template
apiVersion: extensions/v1beta1
kind: Deployment
metadata: <Object>
spec: <Object>
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>
2、nginx Example
nginx example :
apiVersion: app/v1 # 1.9.0 Previous versions were used apps/v1beta2, By order kubectl api-versions see
kind: Deployment # Specify the role to create the resource / type
metadata: # Metadata of resources / attribute
name: nginx-deployment # The name of the resource , In the same namespace Must be unique in
namespace: xxxx # Namespace
labels:
app: demo # label
spec:
replicas: 3 # Copy number 3
strategy:
rollingUpdate: ## because replicas by 3, Then the whole upgrade ,pod The number is 2-4 Between the two
maxSurge: 1 # When rolling upgrade, it will start first 1 individual pod
maxUnavailable: 1 # Maximum allowed for rolling upgrade Unavailable Of pod Number
selector: # Defines a label selector , Deploy what needs to be managed pod( Those with this label will be managed ) Need to be in pod The template defines
matchLabels:
app: web-server
template: # here Pod The definition of
metadata:
labels: #Pod Of label
app: web-server
spec: # Template specification
containers:
- name: nginx # The name of the container
image: nginx:1.12.1 # Image address of the container
command: [ "/bin/sh","-c","cat /etc/config/path/to/special-key" ] # Start command
args: # Launch parameters
- '-storage.local.retention=$(STORAGE_RETENTION)'
- '-storage.local.memory-chunks=$(STORAGE_MEMORY_CHUNKS)'
- '-config.file=/etc/prometheus/prometheus.yml'
- '-alertmanager.url=http://alertmanager:9093/alertmanager'
- '-web.external-url=$(EXTERNAL_URL)'
# If command and args They didn't write , Then use Docker Default configuration .
# If command Yes , but args Didn't write , that Docker The default configuration is ignored and only executed .yaml Of documents command( Without any parameters ).
# If command Not written , but args Yes , that Docker Default configured ENTRYPOINT The command line will be executed , But the parameters are called .yaml Medium args.
# If command and args It's all written , that Docker The default configuration is ignored , Use .yaml Configuration of .
imagePullPolicy: IfNotPresent
# IfNotPresent : The default value is , If there is a local image, use the local image , Don't pull , If not, pull
# Always: Always pull
# Never: Use only local images , Never pull
livenessProbe:
# Express container Is it in live state . If LivenessProbe Failure ,LivenessProbe Will be notified kubelet Corresponding container Not healthy .
# And then kubelet take kill fall container, And according to RestarPolicy Carry out further operations . By default LivenessProbe The initialization value is... Before the first detection Success, If container Not provided LivenessProbe, It's also thought to be Success;
httpGet:
path: /health # If there is no heartbeat detection interface, it will be /
port: 8080
scheme: HTTP
initialDelaySeconds: 60 ## How long does it take to run the test after startup
timeoutSeconds: 5
successThreshold: 1
failureThreshold: 5
readinessProbe:
readinessProbe:
httpGet:
path: /health # If there is no heartbeat detection interface, it will be /
port: 8080
scheme: HTTP
initialDelaySeconds: 30 ## How long does it take to run the test after startup
timeoutSeconds: 5
successThreshold: 1
failureThreshold: 5
resources: ##CPU Memory limit
requests:
cpu: 2
memory: 2048Mi
limits:
cpu: 2
memory: 2048Mi
env: ## Through environment variables , Direct delivery pod= Customize Linux OS environment variable
- name: LOCAL_KEY # Local Key
value: value
- name: CONFIG_MAP_KEY # Bureau strategy can be used configMap Configuration of Key,
valueFrom:
configMapKeyRef:
name: special-config #configmap Find name by special-config
key: special.type # find name by special-config in data Under the key
ports:
- name: http
containerPort: 8080 # Yes service Exposed port
volumeMounts: # mount volumes Disk defined in
- name: log-cache
mount: /tmp/log
- name: sdb # Common usage , The volume is destroyed following the container , Mount a directory
mountPath: /data/media
- name: nfs-client-root # How to mount the hard disk directly , If you mount the nfs Directory to /mnt/nfs
mountPath: /mnt/nfs
- name: example-volume-config # Advanced usage No 1 Kind of , take ConfigMap Of log-script,backup-script Mount to respectively /etc/config A relative path under the directory path/to/... Next , If there is a file with the same name , Directly covered .
mountPath: /etc/config
- name: rbd-pvc # Advanced usage No 2 in , mount PVC(PresistentVolumeClaim)
# Use volume take ConfigMap Mount directly as a file or directory , Each of them key-value Key value pairs will generate a file ,key For the file name ,value For content ,
volumes: # Define the disk to it volumeMounts mount
- name: log-cache
emptyDir: {
}
- name: sdb # Mount the directory on the host
hostPath:
path: /any/path/it/will/be/replaced
- name: example-volume-config # for ConfigMap File content to the specified path to use
configMap:
name: example-volume-config #ConfigMap Chinese name
items:
- key: log-script #ConfigMap Medium Key
path: path/to/log-script # Specify a relative path under the directory path/to/log-script
- key: backup-script #ConfigMap Medium Key
path: path/to/backup-script # Specify a relative path under the directory path/to/backup-script
- name: nfs-client-root # For mounting NFS Storage type
nfs:
server: 10.42.0.55 #NFS Server address
path: /opt/public #showmount -e Take a look at the path
- name: rbd-pvc # mount PVC disk
persistentVolumeClaim:
claimName: rbd-pvc1 # Mount the applied pvc disk
3、SERVICE The configuration template
apiVersion: v1
kind: Service
matadata: # Metadata
name: string #service The name of
namespace: string # Namespace
labels: # Custom tag attribute list
- name: string
annotations: # Custom annotation property list
- name: string
spec: # Detailed description
selector: [] #label selector To configure , Will choose to have label Labeled Pod As management Range
type: string #service The type of , Appoint service Access to , The default is clusterIp
clusterIP: string # Virtual service address
sessionAffinity: string # Do you support session
ports: #service List of ports to be exposed
- name: string # Port name
protocol: string # Port agreement , Support TCP and UDP, Default TCP
port: int # Port number of the service listening
targetPort: int # Need to forward to the back end Pod Port number
nodePort: int # When type = NodePort when , Specify the port number mapped to the physical machine
status: # When spce.type=LoadBalancer when , Set the address of the external load balancer
loadBalancer: # External load balancer
ingress: # External load balancer
ip: string # External load balancer Ip Address values
hostname: string # Host name of the external load balancer
4、Pod The configuration template
apiVersion: v1 # Mandatory , Version number , for example v1, Version number must be available kubectl api-versions Query to .
kind: Pod # Mandatory ,Pod
metadata: # Mandatory , Metadata
name: string # Mandatory ,Pod name
namespace: string # Mandatory ,Pod The namespace to which it belongs , The default is "default"
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 Alawys Download image IfnotPresent Indicates that the local image is preferred , Otherwise download the image ,Nerver Indicates that only local images are used
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 ,Always Indicates that once the operation is terminated in any way ,kubelet Will restart ,OnFailure Only Pod In a 0 Exit code exit to restart ,Nerver Indicates that it is no longer necessary to restart Pod
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
nfs: # The type is NFS The storage volume of
server: 192.168.66.50 #nfs The server ip Or domain name
path: "/test" #nfs Server shared directory
persistentVolumeClaim: # The type is persistentVolumeClaim The storage volume of
claimName: test-pvc # The name must be correct , It uses kind by PersistentVolumeClaim Medium name
5、 Quickly generate YAML file
1、 command
kubectl run --image=nginx my-deploy -o yaml --dry-run >my-deploy.yaml
kubectl create -f deploy-nginx.yaml -o yaml --dry-run >my-deploy.yaml
kubectl create -f deploy-nginx.yaml -o json --dry-run >my-deploy.json # Specify the output json Format
--image # Specify the template image
my-deploy # Run tag name
--dry-run # Just test run , It won't actually run pod
-o yaml # Specify the output format
2、 Inquire about Pod The fields of the container, the resources, the internal documents
kubectl explain pods # Each level of instruction has field information
kubectl explain pods.spec
kubectl explain pods.spec.containers
边栏推荐
- [graphics] hair simulation in tressfx
- Vs+qt multithreading implementation -- run and movetothread
- 【Transform】【NLP】首次提出Transformer,Google Brain团队2017年论文《Attention is all you need》
- How can entrepreneurial teams implement agile testing to improve quality and efficiency? Voice network developer entrepreneurship lecture Vol.03
- Global and Chinese market of air cargo logistics 2022-2028: Research Report on technology, participants, trends, market size and share
- Functional modules and application scenarios covered by the productization of user portraits
- Yolov5系列(一)——网络可视化工具netron
- 【Transform】【实践】使用Pytorch的torch.nn.MultiheadAttention来实现self-attention
- . Net six design principles personal vernacular understanding, please correct if there is any error
- App全局异常捕获
猜你喜欢
[engine development] in depth GPU and rendering optimization (basic)
Kubernetes帶你從頭到尾捋一遍
What is embedding (encoding an object into a low dimensional dense vector), NN in pytorch Principle and application of embedding
B2020 分糖果
【Transform】【NLP】首次提出Transformer,Google Brain团队2017年论文《Attention is all you need》
What is one hot encoding? In pytoch, there are two ways to turn label into one hot coding
Can‘t connect to MySQL server on ‘localhost‘
【云原生训练营】模块八 Kubernetes 生命周期管理和服务发现
Matplotlib drawing label cannot display Chinese problems
Remote server background hangs nohup
随机推荐
Kubernetes - YAML文件解读
Using Tengine to solve the session problem of load balancing
Remote server background hangs nohup
复合类型(自定义类型)
[engine development] in depth GPU and rendering optimization (basic)
Yolov5进阶之八 高低版本格式转换问题
TPS61170QDRVRQ1
高并发下之redis锁优化实战
【注意力机制】【首篇ViT】DETR,End-to-End Object Detection with Transformers网络的主要组成是CNN和Transformer
XWiki安装使用技巧
5.4-5.5
Matplotlib drawing label cannot display Chinese problems
[graphics] adaptive shadow map
Byte practice surface longitude
Center and drag linked global and Chinese markets 2022-2028: Research Report on technology, participants, trends, market size and share
在MapReduce中利用MultipleOutputs输出多个文件
Use of Tex editor
Kubernetes 进阶训练营 Pod基础
Global and Chinese market of air cargo logistics 2022-2028: Research Report on technology, participants, trends, market size and share
Puppet自动化运维排错案例