k8s资源清单
资源清单就是k8s当中用来定义pod的文件,语法格式遵循yaml语法,在yaml当中可以定义控制器类型,元数据,容器端口号等等等....,也可以针对于清单对pod进行删除等操作。
我们可以用kubectl get命令输出一个pod的配置清单,自主式pod清单定义格式如下:

[root@master ~]# kubectl get pods nginx-6799fc88d8-648cn -o yaml apiVersion: v1 kind: Pod metadata: annotations: cni.projectcalico.org/containerID: 03392441c892b616c7f1bf7ed1a412cdb14a8af20bc0cf67c350d7b87a1872a1 cni.projectcalico.org/podIP: 10.101.11.3/32 cni.projectcalico.org/podIPs: 10.101.11.3/32 creationTimestamp: "2022-05-09T07:57:11Z" deletionGracePeriodSeconds: 30 deletionTimestamp: "2022-05-13T02:35:12Z" generateName: nginx-6799fc88d8- labels: app: nginx pod-template-hash: 6799fc88d8 name: nginx-6799fc88d8-648cn namespace: default ownerReferences: - apiVersion: apps/v1 blockOwnerDeletion: true controller: true kind: ReplicaSet name: nginx-6799fc88d8 uid: ab88c364-c138-468d-b0cb-a21bfa23e432 resourceVersion: "25980" uid: 1a471540-a745-4a97-87e1-cc072a56108e spec: containers: - image: nginx imagePullPolicy: Always name: nginx resources: {} terminationMessagePath: /dev/termination-log terminationMessagePolicy: File volumeMounts: - mountPath: /var/run/secrets/kubernetes.io/serviceaccount name: kube-api-access-7cm6p readOnly: true dnsPolicy: ClusterFirst enableServiceLinks: true nodeName: node2 preemptionPolicy: PreemptLowerPriority priority: 0 restartPolicy: Always schedulerName: default-scheduler securityContext: {} serviceAccount: default serviceAccountName: default terminationGracePeriodSeconds: 30 tolerations: - effect: NoExecute key: node.kubernetes.io/not-ready operator: Exists tolerationSeconds: 300 - effect: NoExecute key: node.kubernetes.io/unreachable operator: Exists tolerationSeconds: 300 volumes: - name: kube-api-access-7cm6p projected: defaultMode: 420 sources: - serviceAccountToken: expirationSeconds: 3607 path: token - configMap: items: - key: ca.crt path: ca.crt name: kube-root-ca.crt - downwardAPI: items: - fieldRef: apiVersion: v1 fieldPath: metadata.namespace path: namespace status: conditions: - lastProbeTime: null lastTransitionTime: "2022-05-09T07:57:11Z" status: "True" type: Initialized - lastProbeTime: null lastTransitionTime: "2022-05-13T02:29:26Z" status: "False" type: Ready - lastProbeTime: null lastTransitionTime: "2022-05-09T07:58:20Z" status: "True" type: ContainersReady - lastProbeTime: null lastTransitionTime: "2022-05-09T07:57:11Z" status: "True" type: PodScheduled containerStatuses: - containerID: docker://f5528452cb68da2aabca32f2714ed0f45c59adb5c9b473fcd77850bc07e97881 image: nginx:latest imageID: docker-pullable://nginx@sha256:859ab6768a6f26a79bc42b231664111317d095a4f04e4b6fe79ce37b3d199097 lastState: {} name: nginx ready: true restartCount: 0 started: true state: running: startedAt: "2022-05-09T07:58:19Z" hostIP: 192.168.248.130 phase: Running podIP: 10.101.11.3 podIPs: - ip: 10.101.11.3 qosClass: BestEffort startTime: "2022-05-09T07:57:11Z"
也可以用kubectl create 命令加--dry-run 创建一个yaml文件
[root@master ~]# kubectl create deployment web --image=nginx -oyaml --dry-run W0809 15:15:03.369658 13648 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: {}
资源清单常用字段
1. apiversion
用来指定api的版本,定义的语法格式为group/version,比如我们要定义deployment控制器,那么我们的apiVersion:apps/v1,如果我们要定义自主式pod,那么需要定义apiVersion:v1,如果要获取有哪些apiVersion可以用如下命令

[root@master ~]# kubectl api-versions admissionregistration.k8s.io/v1 admissionregistration.k8s.io/v1beta1 apiextensions.k8s.io/v1 apiextensions.k8s.io/v1beta1 apiregistration.k8s.io/v1 apiregistration.k8s.io/v1beta1 apps/v1 authentication.k8s.io/v1 authentication.k8s.io/v1beta1 authorization.k8s.io/v1 authorization.k8s.io/v1beta1 autoscaling/v1 autoscaling/v2beta1 autoscaling/v2beta2 batch/v1 batch/v1beta1 certificates.k8s.io/v1 certificates.k8s.io/v1beta1 coordination.k8s.io/v1 coordination.k8s.io/v1beta1 crd.projectcalico.org/v1 discovery.k8s.io/v1 discovery.k8s.io/v1beta1 events.k8s.io/v1 events.k8s.io/v1beta1 extensions/v1beta1 flowcontrol.apiserver.k8s.io/v1beta1 networking.k8s.io/v1 networking.k8s.io/v1beta1 node.k8s.io/v1 node.k8s.io/v1beta1 policy/v1 policy/v1beta1 rbac.authorization.k8s.io/v1 rbac.authorization.k8s.io/v1beta1 scheduling.k8s.io/v1 scheduling.k8s.io/v1beta1 storage.k8s.io/v1 storage.k8s.io/v1beta1 v1
2.kind
kind字段主要用于定义控制器类型,指的是yml文件定义的资源类型和角色,比如:我们想定义一个自助式pod,那么我们就应该定义kind:Pod,如果我们要定义一个deployment控制器管理的pod,那么我们就应该定义kind:Deployment
3.metadate 元数据
对于metadata字段为元数据,我们已经知道k8s是通过标签选择器的方式管理pod,因此,在metadata当中最重要的就是标签,我们可以在metadata当中定义名称空间,标签等,我们如果想查看metadata下可以定义哪些元数据可以使用kubectl explain pod.metadata命令来查看
labels:标签选择器,labels的值决定service控制器关联pod的重要选项
name:这里是自主式pod名称,如果是控制器pod,这里是控制器名称
namespace:名称空间,默认为default名称空间
annotations:资源注解,这里跟labels很像,都是键值对,但是不同点是,不能用于挑选资源对象,仅用于“元数据”
4.spec字段
spec字段用来定义期望容器达到的状态,在spec字段当中可以定义多个容器,容器的名称,容器的镜像,拖取容器镜像的方式,暴露的端口号,存储卷,容器个数等,也就是说真正定义pod是在spec字段当中定义的。
spec: containers: 容器列表定义 - image: nginx 用到的镜像名称 imagePullPolicy: Always 定义镜像的拉取策略,一共是有三种方式 1、Always 每次都尝试重新拉取镜像 2、Never 表示只使用本地镜像 3、IfNotPresent 如果有本地镜像就使用本地镜像,没有就在线拉取 默认Always name: nginx 定义容器的名字 resources: {} terminationMessagePath: /dev/termination-log terminationMessagePolicy: File volumeMounts: 容器内部的存储卷配置 - mountPath: /var/run/secrets/kubernetes.io/serviceaccount 指定可以被容器挂载存储卷的路径 name: kube-api-access-7cm6p 指定可以被容器挂载的存储卷的名称 readOnly: true 设置存储卷的的读写模式,true或者false,默认是true 读写模式 dnsPolicy: ClusterFirst enableServiceLinks: true nodeName: node2 preemptionPolicy: PreemptLowerPriority priority: 0 restartPolicy: Always 定义pod的重启策略,一般有三种模式1、 Always pod一旦终止运行,无论容器是怎样退出的kubelet都将重启它 2、OnFailure 只有pod在非0退出码退出时,kubelet才将容器重启 3、Never 在pod终止时不重启。 schedulerName: default-scheduler securityContext: {} serviceAccount: default serviceAccountName: default terminationGracePeriodSeconds: 30 tolerations: - effect: NoExecute key: node.kubernetes.io/not-ready operator: Exists tolerationSeconds: 300 - effect: NoExecute key: node.kubernetes.io/unreachable operator: Exists tolerationSeconds: 300 volumes: - name: kube-api-access-7cm6p projected: defaultMode: 420 sources: - serviceAccountToken: expirationSeconds: 3607 path: token - configMap: items: - key: ca.crt path: ca.crt name: kube-root-ca.crt - downwardAPI: items: - fieldRef: apiVersion: v1 fieldPath: metadata.namespace path: namespace
查看spec详细用法命令
kubectl explain pod.spec

root@master ~]# kubectl explain pod.spec KIND: Pod VERSION: v1 RESOURCE: spec <Object> DESCRIPTION: Specification of the desired behavior of the pod. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status PodSpec is a description of a pod. FIELDS: activeDeadlineSeconds <integer> Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer. affinity <Object> If specified, the pod's scheduling constraints automountServiceAccountToken <boolean> AutomountServiceAccountToken indicates whether a service account token should be automatically mounted. containers <[]Object> -required- List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated. dnsConfig <Object> Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy. dnsPolicy <string> Set DNS policy for the pod. Defaults to "ClusterFirst". Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly to 'ClusterFirstWithHostNet'. enableServiceLinks <boolean> EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true. ephemeralContainers <[]Object> List of ephemeral containers run in this pod. Ephemeral containers may be run in an existing pod to perform user-initiated actions such as debugging. This list cannot be specified when creating a pod, and it cannot be modified by updating the pod spec. In order to add an ephemeral container to an existing pod, use the pod's ephemeralcontainers subresource. This field is alpha-level and is only honored by servers that enable the EphemeralContainers feature. hostAliases <[]Object> HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts file if specified. This is only valid for non-hostNetwork pods. hostIPC <boolean> Use the host's ipc namespace. Optional: Default to false. hostNetwork <boolean> Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified. Default to false. hostPID <boolean> Use the host's pid namespace. Optional: Default to false. hostname <string> Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value. imagePullSecrets <[]Object> ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod initContainers <[]Object> List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/ nodeName <string> NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements. nodeSelector <map[string]string> NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/ overhead <map[string]string> Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. This field will be autopopulated at admission time by the RuntimeClass admission controller. If the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. The RuntimeClass admission controller will reject Pod create requests which have the overhead already set. If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value defined in the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. More info: https://git.k8s.io/enhancements/keps/sig-node/20190226-pod-overhead.md This field is alpha-level as of Kubernetes v1.16, and is only honored by servers that enable the PodOverhead feature. preemptionPolicy <string> PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. This field is beta-level, gated by the NonPreemptingPriority feature-gate. priority <integer> The priority value. Various system components use this field to find the priority of the pod. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority. priorityClassName <string> If specified, indicates the pod's priority. "system-node-critical" and "system-cluster-critical" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default. readinessGates <[]Object> If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to "True" More info: https://git.k8s.io/enhancements/keps/sig-network/0007-pod-ready%2B%2B.md restartPolicy <string> Restart policy for all containers within the pod. One of Always, OnFailure, Never. Default to Always. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy runtimeClassName <string> RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the "legacy" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://git.k8s.io/enhancements/keps/sig-node/runtime-class.md This is a beta feature as of Kubernetes v1.14. schedulerName <string> If specified, the pod will be dispatched by specified scheduler. If not specified, the pod will be dispatched by default scheduler. securityContext <Object> SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field. serviceAccount <string> DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. Deprecated: Use serviceAccountName instead. serviceAccountName <string> ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/ setHostnameAsFQDN <boolean> If true the pod's hostname will be configured as the pod's FQDN, rather than the leaf name (the default). In Linux containers, this means setting the FQDN in the hostname field of the kernel (the nodename field of struct utsname). In Windows containers, this means setting the registry value of hostname for the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters to FQDN. If a pod does not have FQDN, this has no effect. Default to false. shareProcessNamespace <boolean> Share a single process namespace between all of the containers in a pod. When this is set containers will be able to view and signal processes from other containers in the same pod, and the first process in each container will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both be set. Optional: Default to false. subdomain <string> If specified, the fully qualified Pod hostname will be "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>". If not specified, the pod will not have a domainname at all. terminationGracePeriodSeconds <integer> Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates stop immediately via the kill signal (no opportunity to shut down). If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 30 seconds. tolerations <[]Object> If specified, the pod's tolerations. topologySpreadConstraints <[]Object> TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. Scheduler will schedule pods in a way which abides by the constraints. All topologySpreadConstraints are ANDed. volumes <[]Object> List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了