知识点12---k8s进阶操作方式yaml资源文件

本篇为各位读者介绍操作 k8s 的第二种方式,以 yaml 资源文件的方式去使用 k8s 编排能力。要重点说明的是 yaml 方式 和客户端 kubectl 方式并不是相对独立的,yaml 只是省去了繁琐的命令行参数,以及能够将对应的配置,以资源描述配置文件的方式持久化保存下来,使得集群迁移或者日常操作中能够便捷的拿到一份元数据使用。本篇不扩展 yaml 配置文件是什么,它的各种内容格式有什么含义,需要各位读者自己去看其他资料

如果是刚开始接触,肯定会两眼一抹黑,原因无非就是就算知道 yaml 文件是什么,且前面的知识点内容已经接触了 yaml 方式操作的内容,但是让自己写,无从下手,不知道能写什么。这点 k8s 官方早就考虑好了,使用者可以使用如下命令查看当前使用版本某个资源类型能够配置那些 yaml 配置

bash 复制代码
kubectl explain <资源类型>

[k8sadmin@master01 opt]$ kubectl explain service
KIND:       Service
VERSION:    v1

DESCRIPTION:
    Service is a named abstraction of software service (for example, mysql)
    consisting of local port (for example 3306) that the proxy listens on, and
    the selector that determines which pods will answer requests sent through
    the proxy.
    
FIELDS:
  apiVersion    <string>
    APIVersion defines the versioned schema of this representation of an object.
    Servers should convert recognized schemas to the latest internal value, and
    may reject unrecognized values. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

  kind  <string>
    Kind is a string value representing the REST resource this object
    represents. Servers may infer this from the endpoint the client submits
    requests to. Cannot be updated. In CamelCase. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

  metadata      <ObjectMeta>
    Standard object's metadata. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

  spec  <ServiceSpec>
    Spec defines the behavior of a service.
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

  status        <ServiceStatus>
    Most recently observed status of the service. Populated by the system.
    Read-only. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

配置展示命令,可以通过点的方式查询下一级配置

bash 复制代码
[k8sadmin@master01 test]$ kubectl explain service.metadata
KIND:       Service
VERSION:    v1

FIELD: metadata <ObjectMeta>

DESCRIPTION:
    Standard object's metadata. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
    ObjectMeta is metadata that all persisted resources must have, which
    includes all objects users must create.
    
FIELDS:
  annotations   <map[string]string>
    Annotations is an unstructured key value map stored with a resource that may
    be set by external tools to store and retrieve arbitrary metadata. They are
    not queryable and should be preserved when modifying objects. More info:
    https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations

  creationTimestamp     <string>
    CreationTimestamp is a timestamp representing the server time when this
    object was created. It is not guaranteed to be set in happens-before order
    across separate operations. Clients may not set this value. It is
    represented in RFC3339 form and is in UTC.
    
    Populated by the system. Read-only. Null for lists. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

  deletionGracePeriodSeconds    <integer>
    Number of seconds allowed for this object to gracefully terminate before it
    will be removed from the system. Only set when deletionTimestamp is also
    set. May only be shortened. Read-only.

  deletionTimestamp     <string>
    DeletionTimestamp is RFC 3339 date and time at which this resource will be
    deleted. This field is set by the server when a graceful deletion is
    requested by the user, and is not directly settable by a client. The
    resource is expected to be deleted (no longer visible from resource lists,
    and not reachable by name) after the time in this field, once the finalizers
    list is empty. As long as the finalizers list contains items, deletion is
    blocked. Once the deletionTimestamp is set, this value may not be unset or
    be set further into the future, although it may be shortened or the resource
    may be deleted prior to this time. For example, a user may request that a
    pod is deleted in 30 seconds. The Kubelet will react by sending a graceful
    termination signal to the containers in the pod. After that 30 seconds, the
    Kubelet will send a hard termination signal (SIGKILL) to the container and
    after cleanup, remove the pod from the API. In the presence of network
    partitions, this object may still exist after this timestamp, until an
    administrator or automated process can determine the resource is fully
    terminated. If not set, graceful deletion of the object has not been
    requested.
    
    Populated by the system when a graceful deletion is requested. Read-only.
    More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

  finalizers    <[]string>
    Must be empty before the object is deleted from the registry. Each entry is
    an identifier for the responsible component that will remove the entry from
    the list. If the deletionTimestamp of the object is non-nil, entries in this
    list can only be removed. Finalizers may be processed and removed in any
    order.  Order is NOT enforced because it introduces significant risk of
    stuck finalizers. finalizers is a shared field, any actor with permission
    can reorder it. If the finalizer list is processed in order, then this can
    lead to a situation in which the component responsible for the first
    finalizer in the list is waiting for a signal (field value, external system,
    or other) produced by a component responsible for a finalizer later in the
    list, resulting in a deadlock. Without enforced ordering finalizers are free
    to order amongst themselves and are not vulnerable to ordering changes in
    the list.

  generateName  <string>
    GenerateName is an optional prefix, used by the server, to generate a unique
    name ONLY IF the Name field has not been provided. If this field is used,
    the name returned to the client will be different than the name passed. This
    value will also be combined with a unique suffix. The provided value has the
    same validation rules as the Name field, and may be truncated by the length
    of the suffix required to make the value unique on the server.
    
    If this field is specified and the generated name exists, the server will
    return a 409.
    
    Applied only if Name is not specified. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency

  generation    <integer>
    A sequence number representing a specific generation of the desired state.
    Populated by the system. Read-only.

  labels        <map[string]string>
    Map of string keys and values that can be used to organize and categorize
    (scope and select) objects. May match selectors of replication controllers
    and services. More info:
    https://kubernetes.io/docs/concepts/overview/working-with-objects/labels

  managedFields <[]ManagedFieldsEntry>
    ManagedFields maps workflow-id and version to the set of fields that are
    managed by that workflow. This is mostly for internal housekeeping, and
    users typically shouldn't need to set or understand this field. A workflow
    can be the user's name, a controller's name, or the name of a specific apply
    path like "ci-cd". The set of fields is always in the version that the
    workflow used when modifying the object.

  name  <string>
    Name must be unique within a namespace. Is required when creating resources,
    although some resources may allow a client to request the generation of an
    appropriate name automatically. Name is primarily intended for creation
    idempotence and configuration definition. Cannot be updated. More info:
    https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names

  namespace     <string>
    Namespace defines the space within which each name must be unique. An empty
    namespace is equivalent to the "default" namespace, but "default" is the
    canonical representation. Not all objects are required to be scoped to a
    namespace - the value of this field for those objects will be empty.
    
    Must be a DNS_LABEL. Cannot be updated. More info:
    https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces

  ownerReferences       <[]OwnerReference>
    List of objects depended by this object. If ALL objects in the list have
    been deleted, this object will be garbage collected. If this object is
    managed by a controller, then an entry in this list will point to this
    controller, with the controller field set to true. There cannot be more than
    one managing controller.

  resourceVersion       <string>
    An opaque value that represents the internal version of this object that can
    be used by clients to determine when objects have changed. May be used for
    optimistic concurrency, change detection, and the watch operation on a
    resource or set of resources. Clients must treat these values as opaque and
    passed unmodified back to the server. They may only be valid for a
    particular resource or set of resources.
    
    Populated by the system. Read-only. Value must be treated as opaque by
    clients and . More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency

  selfLink      <string>
    Deprecated: selfLink is a legacy read-only field that is no longer populated
    by the system.

  uid   <string>
    UID is the unique in time and space value for this object. It is typically
    generated by the server on successful creation of a resource and is not
    allowed to change on PUT operations.
    
    Populated by the system. Read-only. More info:
    https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids

至于当前版本有那些资源类型,k8s 也提供了一个展示命令

bash 复制代码
NAME 是全称
SHORTNAMES 是缩写。命令行方式操作可以指定全称,也可以指定缩写
APIVERSION   是当前版本该资源类型使用的api版本,这个字段非常重要,比如你要部署一个没接触过的 k8s 版本,在初始化阶段,核心配置服务的api版本号,就可以在 kubeadm 部署的测试环境下看看
NAMESPACED  表示这个资源它是全局资源(false),还是局部资源(true),如果是个局部资源,则需要归属某个命名空间,不同命名空间是隔离的、
KIND  这一列信息就是使用 yaml 配置文件定义它时使用的枚举标识

[k8sadmin@master01 opt]$ kubectl api-resources
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap
endpoints                         ep           v1                                     true         Endpoints
events                            ev           v1                                     true         Event
limitranges                       limits       v1                                     true         LimitRange
namespaces                        ns           v1                                     false        Namespace
nodes                             no           v1                                     false        Node
persistentvolumeclaims            pvc          v1                                     true         PersistentVolumeClaim
persistentvolumes                 pv           v1                                     false        PersistentVolume
pods                              po           v1                                     true         Pod
podtemplates                                   v1                                     true         PodTemplate
replicationcontrollers            rc           v1                                     true         ReplicationController
resourcequotas                    quota        v1                                     true         ResourceQuota
secrets                                        v1                                     true         Secret
serviceaccounts                   sa           v1                                     true         ServiceAccount
services                          svc          v1                                     true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io/v1        false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io/v1        false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1                false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io/v1              false        APIService
controllerrevisions                            apps/v1                                true         ControllerRevision
daemonsets                        ds           apps/v1                                true         DaemonSet
deployments                       deploy       apps/v1                                true         Deployment
replicasets                       rs           apps/v1                                true         ReplicaSet
statefulsets                      sts          apps/v1                                true         StatefulSet
selfsubjectreviews                             authentication.k8s.io/v1               false        SelfSubjectReview
tokenreviews                                   authentication.k8s.io/v1               false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io/v1                true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io/v1                false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io/v1                false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io/v1                false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling/v2                         true         HorizontalPodAutoscaler
cronjobs                          cj           batch/v1                               true         CronJob
jobs                                           batch/v1                               true         Job
certificatesigningrequests        csr          certificates.k8s.io/v1                 false        CertificateSigningRequest
leases                                         coordination.k8s.io/v1                 true         Lease
endpointslices                                 discovery.k8s.io/v1                    true         EndpointSlice
events                            ev           events.k8s.io/v1                       true         Event
flowschemas                                    flowcontrol.apiserver.k8s.io/v1beta3   false        FlowSchema
prioritylevelconfigurations                    flowcontrol.apiserver.k8s.io/v1beta3   false        PriorityLevelConfiguration
ingressclasses                                 networking.k8s.io/v1                   false        IngressClass
ingresses                         ing          networking.k8s.io/v1                   true         Ingress
networkpolicies                   netpol       networking.k8s.io/v1                   true         NetworkPolicy
runtimeclasses                                 node.k8s.io/v1                         false        RuntimeClass
poddisruptionbudgets              pdb          policy/v1                              true         PodDisruptionBudget
clusterrolebindings                            rbac.authorization.k8s.io/v1           false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io/v1           false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io/v1           true         RoleBinding
roles                                          rbac.authorization.k8s.io/v1           true         Role
priorityclasses                   pc           scheduling.k8s.io/v1                   false        PriorityClass
csidrivers                                     storage.k8s.io/v1                      false        CSIDriver
csinodes                                       storage.k8s.io/v1                      false        CSINode
csistoragecapacities                           storage.k8s.io/v1                      true         CSIStorageCapacity
storageclasses                    sc           storage.k8s.io/v1                      false        StorageClass
volumeattachments                              storage.k8s.io/v1                      false        VolumeAttachment

常用的资源类型如下

缩写 全称 说明
po pods K8s 中最小的可部署计算单元。
deploy deployments pod控制器,用于管理无状态应用的部署、更新和回滚。
svc services 定义一组 Pod 的访问策略,提供统一的网络入口。
ns namespaces 用于在同一个物理集群中进行逻辑资源隔离。
no nodes 集群中的工作节点(物理机或虚拟机)。
rs replicasets 确保指定数量的 Pod 副本始终在运行。
ds daemonsets 确保集群中每个(或特定)节点上都运行一个 Pod 副本。
sts statefulsets 用于管理有状态应用(如数据库),保证 Pod 的顺序性和唯一性。
cm configmaps 存储非机密性的配置数据,可被 Pod 挂载使用。
sec secrets 敏感信息对象(如密码、令牌、密钥、token等)。
pv persistentvolumes 集群中预先分配好的存储资源。
pvc persistentvolumeclaims 用户对存储资源的请求,用于申请 PV。
ing ingresses 管理集群外部到内部服务的 HTTP/HTTPS 路由。
hpa horizontalpodautoscalers 根据 CPU 利用率等指标自动调整 Pod 副本数量。
rc replicationcontrollers 早期版本的副本控制器,现多被 ReplicaSet 取代。
sa serviceaccounts 为 Pod 中的进程访问集群 API 提供身份标识。
crd customresourcedefinitions 用于定义自定义资源类型。
cs componentstatuses 显示集群组件(如 scheduler, controller-manager)的状态。
ep endpoints 存储 Service 后端 Pod 的 IP 地址和端口信息。
ev events 记录集群中发生的事件(如调度失败、扩容等)。
cj cronjobs 基于时间计划的任务调度(类似 Linux Crontab)。
job jobs 运行一次性任务,任务完成后 Pod 终止。
netpol networkpolicies 定义 Pod 之间的网络访问规则(防火墙策略)。
psp podsecuritypolicies 定义 Pod 的安全策略(如特权容器限制)。
pdb poddisruptionbudgets 定义在自愿干扰(如节点维护)期间 Pod 的最小可用数量。
sc storageclasses 定义不同的存储类型,用于动态创建 PV。
csr certificatesigningrequests 向集群请求签署 TLS 证书。
quota resourcequotas 限制命名空间内的资源使用总量(如 CPU、内存上限)。
limits limitranges 限制命名空间内单个 Pod 或容器的资源最小/最大值。

常用的 yaml 配置如下

参数名 字段类型 说明
version String 指定 K8s API 的版本(如 apiVersion: v1)。可以通过 kubectl api-versions 命令查询可用版本。
kind String 定义 YAML 文件创建的资源类型和角色,例如 PodDeploymentService 等。
metadata Object 元数据对象,固定值就写 metadata
metadata.name String 元数据对象的名字,这里由我们编写,比如命名 Pod 的名字。
metadata.namespace String 元数据对象的命名空间,由我们自身定义。
spec Object 详细定义信息,固定值就写 spec
spec.containers[] List 这是 Spec 对象的容器列表定义,是个列表。
spec.containers[].name String 这里定义容器的名字。
spec.containers[].image String 这里定义要用到的镜像名称。
spec.containers[].imagePullPolicy String 定义镜像拉取策略,有三个值可选: 1. Always:每次都重新拉取镜像(默认)。 2. Never:只使用本地镜像。 3. IfNotPresent:本地有则用本地,没有则拉取。
spec.containers[].command[] List 指定容器启动命令,因为是数组可以指定多个,不指定则使用镜像打包时的启动命令。
spec.containers[].args List 指定容器启动命令参数,因为是数组可以指定多个。
spec.containers[].workingDir String 指定容器的工作目录。
spec.containers[].volumeMounts[] List 指定容器内部的存储卷配置。
spec.containers[].volumeMounts[].name String 指定可以被容器挂载的存储卷的名称。
spec.containers[].volumeMounts[].mountPath String 指定可以被容器挂载的存储卷的路径。
spec.containers[].volumeMounts[].readOnly String 设置存储卷路径的读写模式,true 或者 false,默认为读写模式。
spec.containers[].ports[] List 指定容器需要用到的端口列表。
spec.containers[].ports[].name String 指定端口名称。
spec.containers[].ports[].containerPort String 指定容器需要监听的端口号。
spec.containers[].ports[].hostPort String 指定容器所在主机需要监听的端口号,默认跟 containerPort 相同。注意:设置了 hostPort 同一台主机无法启动该容器的相同副本(因为主机的端口号不能相同,这样会冲突)。
spec.containers[].ports[].protocol String 指定端口协议,支持 TCP 和 UDP,默认值为 TCP。
spec.containers[].env[] List 指定容器运行前需设置的环境变量列表。
spec.containers[].env[].name String 指定环境变量名称。
spec.containers[].env[].value String 指定环境变量值。
spec.containers[].resources Object 指定资源限制和资源请求的值(这里开始就是设置容器的资源上限)。
spec.containers[].resources.limits Object 指定容器运行时资源的运行上限。
spec.containers[].resources.limits.cpu String 指定 CPU 限制,单位为 core 数,将用于 docker run --cpu-shares 参数。
spec.containers[].resources.limits.memory String 指定 MEM 内存的限制,单位为 MiB、GiB。
spec.containers[].resources.requests Object 指定容器启动和调度时的资源请求设置。
spec.containers[].resources.requests.cpu String CPU 请求,单位为 core 数,容器启动时初始化可用数量。
spec.containers[].resources.requests.memory String 内存请求,单位为 MiB、GiB,容器启动时初始化可用数量。
spec.restartPolicy String 定义 Pod 的重启策略,可选值为 AlwaysOnFailureNever,默认值为 Always。 1. Always:Pod 一旦终止运行,无论容器如何终止,kubelet 服务都重启它。 2. OnFailure:只有 Pod 以非零退出码终止时,kubelet 才会重启该容器。如果容器正常结束(退出码为 0),则 k8s 将不会重启它。 3. Never:Pod 终止后,kubelet 将退出码报告给 Master,不会重启该 Pod。
spec.nodeSelector Object 定义 Node 的 Label 过滤标签,以 key:value 格式指定。
spec.imagePullSecrets Object 定义 pull 镜像时使用 secret 名称,以 name:secretkey 格式指定。
spec.hostNetwork Boolean 定义是否使用主机网络模式,默认值为 false。设置 true 表示使用宿主机网络,不使用 docker 网桥,同时设置了 true 将无法在同一台宿主机上启动第二个副本。

在书写这些 yaml 文件时,也不要少傻到一个个的去手写,你可以用客户端生成一个大概的模板,改一改沿用就行

bash 复制代码
kubectl create <资源类型> <资源名称> [其他参数] --dry-run=client -o yaml > 文件名.yaml

# 生成用控制器去间接控制容器
kubectl create deployment my-app --image=my-app:v1 --replicas=3 --dry-run=client -o yaml > deploy.yaml
# 假设已经有一个名为 my-app 的 deployment,为它生成service的 yaml
kubectl expose deployment my-app --port=80 --target-port=8080 --type=NodePort --dry-run=client -o yaml > svc.yaml

不过注意,这种方式只能用来偷懒生成一些直观的配置,说白了就是客户端支持那些参数,就可以生成那些配置,而复杂类型的配置就不行了

下面是一些常用的例子

案例一:创建叫做 test 的命名空间

yaml 复制代码
apiVersion: v1
kind: Namespace
metadata:
  name: test  # 命名空间名称
  labels:
    environment: dev # 给命名空间打标签,方便筛选

案例二:直接创建一个Pod,相当于用客户端的 run 命令

yaml 复制代码
apiVersion: v1
kind: Pod
metadata:
  name: my-nginx-pod
  namespace: test  # 指定所属命名空间,不写默认为 default
  labels:
    app: nginx          # 给 Pod 打标签
spec:
  containers:
  - name: nginx-container # 容器名称
    image: nginx:1.18.0     # 镜像名称及版本
    ports:
    - containerPort: 80   # 声明容器监听的端口(仅供文档说明,不实际开放)
    imagePullPolicy: IfNotPresent # 镜像拉取策略:本地有则不拉取,没有则拉取

案例三:生产环境创建Pod,都是通过控制器来实现的

yaml 复制代码
apiVersion: apps/v1 # Deployment 属于 apps API 组
kind: Deployment
metadata:
  name: nginx-deploy
  namespace: test
spec:
  replicas: 2 # 指定 Pod 副本数量
  selector:   # 选择器,用于寻找并管理带有对应标签的 Pod
    matchLabels:
      app: nginx   # 在 1.28.0 版本中如果这个标签对应的Pod是存在的,也就是说用案例二的方式或直接run的,不会影响已存在的Pod,k8s用新的资源去实现,不过为了防止混淆经历不要使用以被使用的标签
  template:   # 指定这个控制器要创建 Pod 时以谁为模板,比如pod崩溃灾难重启等等这种场景
    metadata:
      labels:
        app: nginx # 这里的标签必须与上面的 selector.matchLabels 一致
    spec:
      containers:
      - name: nginx
        image: nginx:1.18.0
        ports:
        - containerPort: 80

案例四:Service (服务暴露)

yaml 复制代码
apiVersion: v1
kind: Service
metadata:
  name: nginx-svc
  namespace: test
spec:
  type: NodePort # 默认类型为ClusterIP
  selector:
    app: nginx    # 将流量转发给带有 app=nginx 标签的 Pod
  ports:
  - port: 80      # Service 自身的端口
    targetPort: 80 # 转发到 Pod 容器的端口
    nodePort: 30080  # 这个不指定是默认用集群配置里的默认范围随机

案例五:解耦配置信息,就相当于在集群中存在一个配置模版

ConfigMap 普通配置

yaml 复制代码
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-app-config
data:
  # 方式一:简单的键值对,这种格式通常用来以容器的环境变量使用
  LOG_LEVEL: "info"
  DB_HOST: "192.168.1.100"
  # 方式二:完整的配置文件内容 (比如 nginx.conf 或 application.yml),这种方式通常用来给容器准备需要默认存在的配置文件
  app.properties: |
    server.port=8080
    redis.url=redis://my-redis:6379

Secret 敏感配置,这里面的配置值必须是 Base64 格式,可以用命令 echo -n '123456' | base64 来生成

yaml 复制代码
apiVersion: v1
kind: Secret
metadata:
  name: my-app-secret
type: Opaque # 通用类型
data:
  DB_USER: cm9vdA==      # 这是 "root" 的 Base64 编码
  DB_PASS: MTIzNDU2      # 这是 "123456" 的 Base64 编码

在其他的资源主体定义的时候就可以使用他们,比如创建一个Pod,你可以让配置以容器的环境变量存在

yaml 复制代码
apiVersion: v1
kind: Pod
metadata:
  name: config-pod-env
spec:
  containers:
  - name: my-app
    image: nginx:1.18.0
    env:
      # 1. 引用 ConfigMap 中的值
      - name: MY_LOG_LEVEL  # 容器内的环境变量名
        valueFrom:
          configMapKeyRef:
            name: my-app-config # 对应的 ConfigMap 名字
            key: LOG_LEVEL      # 对应的键
      # 2. 引用 Secret 中的值
      - name: MY_DB_PASSWORD
        valueFrom:
          secretKeyRef:
            name: my-app-secret
            key: DB_PASS

效果如下

bash 复制代码
[k8sadmin@master01 test]$ kubectl exec -it config-pod-env -- /bin/bash
root@config-pod-env:/# echo $MY_LOG_LEVEL
info
root@config-pod-env:/# echo $MY_DB_PASSWORD
123456

对于文件格式的配置,可以用来以容器内的一个配置文件存在

yaml 复制代码
apiVersion: v1
kind: Pod
metadata:
  name: config-pod-file
spec:
  containers:
  - name: my-app
    image: nginx:1.18.0
    volumeMounts:   # 定义容器的数据卷挂载点
    - name: config-volume
      mountPath: /etc/config  # 普通配置挂载到容器内的这个目录
    - name: secret-volume
      mountPath: /etc/secret  # 敏感信息挂载到另一个目录
      readOnly: true          # 建议设为只读,防止被篡改
  volumes:     # 定义数据卷
  # 定义卷来源 ConfigMap
  - name: config-volume
    configMap:
      name: my-app-config
  # 定义卷来源 Secret
  - name: secret-volume
    secret:
      secretName: my-app-secret

效果如下。可以发现,变量名做文件名,同样的上面以环境变量存在的使用方式,也可以引用配置文件格式的ConfigMap值,但是它会把文件内容扁平化在一行里,和你在linux脚本中给一个变量赋值列表格式的输出结果一样,以空格分割,所以很少这样用

bash 复制代码
[k8sadmin@master01 test]$ kubectl exec -it config-pod-file -- /bin/bash   
root@config-pod-file:/# cd /etc/config
root@config-pod-file:/etc/config# ls
DB_HOST  LOG_LEVEL  app.properties
root@config-pod-file:/etc/config# cd /etc/secret
root@config-pod-file:/etc/secret# ls
DB_PASS  DB_USER
root@config-pod-file:/etc/secret# cat DB_PASS
123456
root@config-pod-file:/etc/secret# 

案例六:最最最最!!最常用的配置就是创建Pod时,指定资源配置

yaml 复制代码
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx-pod
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-nginx-pod
  template:
    metadata:
      labels:
        app: my-nginx-pod
    spec:
      # --- affinity调度策略 ---
      affinity:  
        nodeAffinity:  # 节点亲和
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 1
            preference:
              matchExpressions:
              - key: disktype  # 节点/Pod上标签的键名
                operator: In  # "In" 表示标签的值必须在下面的 values 列表中, NotIn (不在列表中), Exists (存在该键), DoesNotExist (不存在该键)
                values:
                - ssd
      containers:
      - name: app-container
        image: nginx:1.18.0
        # --- 资源管理 ---
        resources:
          requests:      # 调度时保证的最低资源
            cpu: "250m"  # 0.25 核,在k8s中 1核 CPU 是安装 1000m 毫时 使用的,而不是一整个核
            memory: "128Mi"   # Mi是二进制算法 1Mi=1024kb
          limits:        # 允许使用的最大资源上限
            cpu: "500m"
            memory: "256Mi"
        # --- 健康检查 ---
        # 存活探针:如果失败,K8s 会重启容器
        livenessProbe:
          httpGet:
            path: /healthz
            port: 80  # 检测目标端口
          initialDelaySeconds: 30 # 容器启动后等待30秒再开始检查
          periodSeconds: 10       # 每10秒检查一次
        # 就绪探针:如果失败,Service 不会将流量转发给该 Pod
        readinessProbe:
          tcpSocket:
            port: 80  # 检测目标端口
          initialDelaySeconds: 5
          periodSeconds: 10

重点1:调度策略有三种,nodeAffinity(节点亲和)、podAffinity(Pod亲和)、podAntiAffinity(Pod互斥)

重点2:调度策略有两种生效模式,preferredDuringSchedulingIgnoredDuringExecution(尽量满足不强制,多个节点按照符合规则的权重总和决定调度)、requiredDuringSchedulingIgnoredDuringExecution(强制要求,如果调度后节点出现不满足,则k8s有概率驱逐Pod)

以上的案例能够覆盖日常使用中85%的场景,还有一个核心知识点是持久化存储,这个比较重要放在下一篇知识点单独说。以上的yaml文件在使用时,并不是说你要每一类操作都放一个文件, 你可以在一个yam l文件中,不同的操作类型,使用三个横英文横杠---分割, K8s会自动识别,就像前面知识点安装 flannel cni 网络插件,甚至是集群监控插件那样

对于 yaml 文件生效上,只需要执行 kubectl apply -f 文件/yaml文件的一个路径即可,删除对应的资源类型主体只需要执行kubectl delete -f 文件/yaml文件的一个路径即可

相关推荐
尘世壹俗人1 小时前
知识点13---k8s存储持久化
容器·kubernetes·flask
SilentSamsara1 小时前
Kubernetes 网络模型:CNI 插件与 Pod 间通信的底层实现
网络·云原生·容器·架构·kubernetes·k8s
wuxinyan1232 小时前
Java面试题50:Kubernetes 全栈知识体系之一
java·kubernetes·面试题
牛奶咖啡133 小时前
Docker容器实践——Docker常用基础镜像的解析与选择
docker·容器·docker基础镜像·docker基础镜像选择·docker基础镜像最佳实践·docker基础镜像的分类·docker基础镜像的对比
java_logo3 小时前
Docker 部署 Open WebUI + Ollama 完整教程(Windows / Linux 通用)—— 打造自己的本地OpenAI
linux·docker·容器·ollama·open-webui·open-webui部署·open-webui教程
杨浦老苏3 小时前
AI使用追踪和代理网关GoModel
人工智能·docker·ai·api·群晖
程序员老邢3 小时前
【技术底稿 23】Ollama + Docker + Ubuntu 部署踩坑实录:网络通了,参数还在调
java·经验分享·后端·ubuntu·docker·容器·milvus
小夏子_riotous3 小时前
Docker学习路径——8、Dockerfile
linux·运维·docker·容器·系统架构·centos·运维开发
2601_955256473 小时前
服务器日志管理最佳实践:logrotate配置详解、云日志服务对比与Docker日志限制方案
运维·服务器·docker