Quick start kubernetes (k8s) - resource list

Big data brother 2021-02-04 13:38:35
quick start kubernetes k8s resource

In the last article, we set up private services for enterprises , This article introduces k8s Medium Resource list Most of this article is theoretical . Patience will refresh your understanding of k8s The cognitive .

One 、 k8s The resource

1.1 What is resource ?

K8s All the content in is abstracted as resources , After resource instantiation , It's called object

1.2 K8S What resources exist in

  1. Workload resources (workload): Pod、ReplicaSet、Deployment、StatefulSet、DaemonSet、Job、CronJob(ReplicationController stay v1.11 The version is obsolete )
  2. Service discovery and load balancing resources (ServiceDiscoveryLoadBalance): Service、Ingress、...
  3. Configuration and storage resources : Volume( Storage volume )、CSI( Container storage interface , Can expand a variety of third-party storage volumes )
  4. 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 )
  5. Cluster-level resources : Namespace、Node、Role、ClusterRole、RoleBinding、ClusterRoleBinding
  6. Metadata resources : HPA、PodTemplate、LimitRange

Two 、 Resource list

stay k8s in , In general use yaml Format to create what we expect pod, In this way yaml Documents are commonly referred to as Resource list

3、 ... and 、 Common field explanations

3.1 Fields that must exist

Be careful : If you don't write all of them, you won't let them run pod Of

Parameter name

Field type




This means k8s API Version of , At present, it is basically v1, Sure use kubectl api-version Command query



This means yam File defined resource types and roles , such as :Pod



Metadata object , The fixed value is written as metadata



The name of the metadata object , Here we write , For example, Ru Ming POd Name

metadata namespace


The namespace of the metadata object , By our own definition



Define objects in detail , The fixed value is written as Spec

spec containers[]


Here is Spec Object's container list definition , It's a list

spec containers[].name


Here is the name of the container

spec containers[]. image


Here we define the image name to be used

Define a pod Run tests

  1. Write a yaml file
  2. Use kubectl Create
  3. Use get pod see

1、 establish pod.yaml file

[root@k8s-master01 ~]# vim pod.yaml
apiVersion: v1
kind: Pod
name: myapp-pod
app: myapp
version: v1
- name: app
image: hub.dashujulaoge.com/library/myapp:v1

2、 establish pod

[root@k8s-master01 ~]# kubectl create -f pod.yam

3、 Use get pod Check the status ( Running successfully )

3.2 Main object

The main : Let's see if the content is available or not , If not, the system will add a default value

Parameter name

Field type


spec containers[]. name


Define the name of the container

spec containers[]. image


Define the image name to use

spec containers[]. imagePullPolicy


Take the road of justice and strategy , Yes Always、 NeverIfNotPresent Three values are optional (1) Always: It means that you try to pull the mirror image again every time (2) Never: Indicates that only local images are used (3) IfNotPresent: If there is a local image, use the local image , If not, pull the online image . If none of the above three values are set , The default is Always.

spec containers[]. command[]


Point out the container start command , Because it's an array, you can specify multiple , If not specified, the startup command used in image packaging is used .

spec containers[]. args[]


Specify the container start command parameters , Because it's an array, you can specify multiple .

spec containers[]. workingDir


Specify the working directory of the container

spec containers[]. volumeMounts[]


Specifies the storage volume configuration inside the container

spec containers[]. volumeMounts[].name


Specifies the name of the storage volume that can be mounted by the container

spec containers[]. volumeMounts[].mountrPath


Specify the path of the storage that can be mounted

spec containers[]. volumeMounts[].readOnly


Set the read / write mode of the storage volume path ,ture perhaps false, I think the read-write mode

spec containers[]. ports[]


Point out the full list of containers to use

spec containers[].ports[]. name


Specify the port name

spec containers[].ports[]. containerPort


Specify the port number that the container needs to listen on

spec containers[]. ports[]. hostPort


First determine the port number of the host where the container is located , The default is to follow the above containerPort identical , Pay attention to the settings hostPort The same host cannot start the same copy of the container ( Because the port number of the host cannot be the same , It's going to conflict )

spec containers[]. ports[]. protocol


Specify the port protocol , Support TCP and UDP, The recognition value is TCP

spec containers[]. env[]


Specifies the list of environment variables to be set before the container runs

spec containers[].env[]. name


Specify the environment variable name

spec containers[].env[] value


Refers to the value of the environment variable

spec containers[]. resources


Specify the resource limit and the value of the source request ( The first step here is to set the resource cap of the container )

spec containers[]. resources.limits


Specifies to set the upper run limit of the container runtime resource

spec containers[]. resources.limits. cpu


Appoint CPU The limitation of , Unit is core Count , Will be used for docker run-cpu- shares Parameters ( Here is the previous article Pod Resource constraints have been mentioned )

spec containers[].resources.limits. memory


Appoint MEM Memory limit , Unit is MIB、GiB

spec containers[]. resources. requests


Specify the restriction settings for container startup and scheduling

spec containers[]. resources. requests. cpu


CPU request , Unit is core Count , Initialize the available quantity when the container starts

spec containers[]. resources. requests memory


Memory request , Unit is MIB、GiB, Number of initialization available for container startup

3.3 Additional parameter items

Parameter name

Field type


spec. restartPolicy


Definition Pod The way to restart , Optional value is Alays、 Onfailure, The default value is Always.1 Always:Pod- And stop running , No matter how the container terminates , kubelet The service will restart it .2. failure: Only Pod When terminated with a nonzero exit code , kubeletオ Will restart the container . If the container ends normally ( The exit code is 0), be kubelet It won't restart 3. Never:Pod After termination , kubelet Report the exit code to Master, It won't restart Pod

spec. nodeSelector


Definition Node Of Labe Filter tags , With key: value Format designation

spec. imagePullSecrets


Definition pu Use when you like secrets name , With name secretkey Format designation



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 , Also set up tue You will not be able to start a second copy on the same host .

Four 、 Container life cycle

4.1 Pod Life cycle architecture diagram

4.2 Init Containers

Pod Can have multiple containers , Applications run in containers , But it may also have one or more started before the application container Init Containers

Init Containers are very similar to ordinary containers , Except for the following two points :

* Init Containers always run until successful completion

* Every Init All containers must be in the next Init Successfully completed before the container started

If Pod Of Init Container failed ,Kubernetes Will restart the Pod, until Init Until the container succeeds . However , If Pod Corresponding restartPolicy by Never, It won't restart

4.3 Init The function of the container

because Init The container has a separate image from the application container , So their startup related code has the following advantages :

* They can contain and run Utilities , But for safety reasons , It is not recommended to include these utilities in the application container image

* They can include using tools and custom code to install , But not in the application image . for example , There's no need to create a mirror FROM Another mirror image , Just use something like sed、awk、python or dig Such a tool .

* Application mirroring can separate the roles created and deployed , There's no need to combine them to build a separate mirror .

* Init Container usage LinuxNamespace, So it has a different view of the file system than the application container . therefore , They can have access to Secret Authority , The application container cannot .

* They have to run before the application container starts , And the application container runs in parallel , therefore Init Containers can provide a simple way to block or delay the start of an application container , Until a set of prerequisites .

4.4 Init Special instructions

* stay Pod During startup ,Init Containers start in sequence after network and data volume initialization . Each container must successfully exit before the next container starts .

* If you exit due to a run or failure , Will cause the container to fail to start , It will be based on Pod Of restartPolicy The specified policy . However , If Pod Of restartPolicy Set to Always,Init When the container fails, it uses RestartPolicy Strategy .

* Of all the Init The container didn't succeed before ,Pod It will not become Ready state .Init The port of the container will not be in Service Gathering in the middle . Initializing Pod be in Pending state , But it should be Initializing The status is set to true.

* If Pod restart , all Init The container must be reexecuting ..

* # Yes Init Containers spec Changes to the container are limited to image Field , Modifying other fields will not take effect . change Init Container of image Field , It is equivalent to restarting the system Pod.

* Init The container has all the fields that apply the container . except readinessProbe, because Init Container cannot be defined as different from complete (completion) Ready for (readiness) Other states besides . This is enforced during validation .

* stay Pod Each of the app and Init The name of the container must be unique ; Share the same name with any other container , Will throw an error during validation .

4.5 Container probe

The probe is made by kubelet Periodic diagnostics performed on containers . To perform a diagnosis ,kubelet Call the Handler. There are three types of handlers :

  • ExecAction: Execute the specified command in the container . If the return code is 0 The diagnosis is successful .
  • TCPSocketAction: For the container on the specified port IP address TCP Check . If the port is open , The diagnosis is considered successful .
  • HTTPGetAction: For containers on the specified port and path IP Address execution HTTPGet request . If the status code of the response is greater than or equal to 200 And less than 400, The diagnosis is considered successful .

Each probe will produce one of the following three results :

  • success : The container passed the diagnosis .
  • Failure : Container failed diagnosis .
  • Unknown : The diagnosis failed , So no action will be taken

4.6 Detection mode

livenessProbe: Indicates whether the container is running . If survival detection fails , be kubelet Will kill the container , And the container will be affected by its restart policy . If the container does not provide a survival probe , The default state is Success

readinessProbe: Indicates whether the container is ready for service requests . If ready detection fails , The endpoint controller will start with Pod All that matches Service Delete the Pod Of IP Address . The ready state before the initial delay defaults to Failure. If the container does not provide a ready probe , The default state is Success

4.7 PodHook

Podhook( hook ) By Kubernetes Managed kubelet Sponsored , When a process in a container starts or terminates , This is included in the life cycle of the container . It can also be Pod All containers in are configured with hook

Hook There are two types of :

  • exec: Execute a command
  • HTTP: send out HTTP request

4.8 Restart strategy

PodSpec There is one of them. restartPolicy Field , The possible value is Always、OnFailure and Never. The default is Always.restartPolicy Apply to Pod All containers in .restartPolicy Only through... On the same node kubelet Restart the container . The failed container is created by kubelet Exponential backoff delay up to five minutes (10 second ,20 second ,40 second ...) Restart , And reset after 10 minutes of successful execution . Such as Pod Described in the documentation , Once bound to a node ,Pod Will never rebind to another node .

4.9 PodHase Possible values

  • Hang up (Pending):Pod Has been Kubernetes The system accepts , But one or more container images have not yet been created . Waiting time includes scheduling Pod Time to download the image and time to download the image through the network , It may take some time
  • Running (Running): The Pod Already bound to a node ,Pod All containers in have been created . At least one container is running , Or it's starting or restarting
  • success (Succeeded):Pod All containers in were successfully terminated , And it won't restart
  • Failure (Failed):Pod All containers in have been terminated , And at least one container is terminated for failure . in other words , The container is not 0 The state exits or is terminated by the system
  • Unknown (Unknown): For some reason can't get Pod The state of , It's usually because it's related to Pod Host communication failure

5、 ... and 、 Fan benefits and software access

Some of them are just beginning to learn k8s I don't have a goal , I don't know how to learn , as well as k8s How to learn what to learn . I'm here to prepare a Learning flow chart can be obtained by interested partners WeChat search 【 Big data brother 】 reply 【k8s Learning flow chart 】 Can get .

Software access

Friends may need a lot of image files after installation, and the download is very long , Big data brother is here to prepare for you , WeChat search official account 【 Big data brother 】 reply 【k8s software package 】 Can get

Other benefits

WeChat official account search 【 Big data brother 】 Can get 200 A customized resume template for you 、 Big data interview questions 、 Business interview questions ..... wait .

Order one Looking at You'd better see

This article is from WeChat official account. - Big data brother (gh_275d810750e6) , author : Big data brother

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2020-12-06

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

本文为[Big data brother]所创,转载请带上原文链接,感谢

  1. K8s命令篇-Kubernetes工作实用命令集结号
  2. K8s command chapter - kubernetes working practical command collection number
  3. San Wai doesn't even know how to change MySQL table DDL
  4. HTTP series - detailed explanation of message structure
  5. MySQL 存储引擎 MyISAM 与 InnoDB 区别
  6. The difference between MySQL storage engine MyISAM and InnoDB
  7. 《算法竞赛入门经典——训练指南》实用数据结构
  8. Practical data structure of "Introduction to algorithm competition classic training guide"
  9. Hive的数据压缩介绍及使用
  10. Introduction and use of hive's data compression
  11. Please put away this database interview summary for spring recruitment
  12. Redis:23---info命令总结
  13. Redis:23---info Command summary
  14. What's in HTTP header?
  15. Linux commands 4-find, locate
  16. linuxNote1_ user management
  17. Brief description of Tencent cloud redis console parameters
  18. Redis transaction management
  19. Regular expression in Java
  20. Linux text processing
  21. Don't download JDK any more: elasticsearch's first big hole in the domestic arm environment
  22. Getting started with spring boot 2. X: getting started with spring MVC request mapping (@ requestmapping)
  23. Introduction to MySQL architecture
  24. Linux foundation day02
  25. [javap6 outline] Spring Court: how to select the technology of fuse framework? Sentinel or hystrix?
  26. Chinese user guide of parallel SSH under Linux
  27. Top of BPF: insight into Linux system and application performance
  28. Various parameter configuration of docker
  29. JQuery level selector (descendant, descendant selector)
  30. Interesting JavaScript - precision loss and implicit type conversion
  31. Database: built in functions of MySQL