保姆级K8s的Pod的yml配置文件完整示例与参数含义解释

Pod的YAML配置文件示例与参数解析

YAML 示例完整解析

关键字段详解

1. apiVersion 和 kind

2. metadata(元数据)

3. spec.containers(主容器配置)

4. volumes(存储卷定义)

5. initContainers(初始化容器)

YAML 示例的典型场景

注意事项 


YAML 示例完整解析

# API 版本和资源类型声明
apiVersion: v1
kind: Pod
metadata:
  name: web-app-prod-01          # 命名规范: 应用名-环境-序号 (便于监控和排查)
  namespace: production          # 强制指定命名空间,隔离生产环境
  labels:
    app: web-app                 # 应用标识 (与Service/Deployment对齐)
    env: prod                    # 环境标识 (prod/staging/dev)
    tier: frontend               # 层级标识 (frontend/backend/cache)
  annotations:
    prometheus.io/scrape: "true" # 集成监控:允许Prometheus自动抓取指标
    prometheus.io/port: "8080"   # 指标暴露端口
    gitCommit: "a1b2c3d"         # 记录代码版本,便于追踪

# --- 核心配置开始 ---
spec:
  # 安全上下文 (最小权限原则)
  securityContext:
    runAsNonRoot: true           # 禁止以root用户运行
    runAsUser: 1000              # 指定普通用户UID
    runAsGroup: 3000             # 指定组GID
    fsGroup: 3000                # 挂载卷的GID权限
    seccompProfile:
      type: RuntimeDefault       # 启用Seccomp安全过滤

  # 调度策略 (优化资源利用)
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: node-type       # 指定节点标签
            operator: In
            values:
            - optimized-cpu
    podAntiAffinity:             # 避免Pod堆叠在同一节点
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchExpressions:
            - key: app
              operator: In
              values:
              - web-app
          topologyKey: kubernetes.io/hostname

  tolerations:                   # 容忍节点污点
  - key: "dedicated"
    operator: "Equal"
    value: "web"
    effect: "NoSchedule"

  # 容器定义
  containers:
  - name: web-server
    image: registry.internal.com/prod/web-app:1.5.3  # 使用私有仓库和确定版本
    imagePullPolicy: IfNotPresent                   # 避免latest标签风险
    ports:
    - name: http
      containerPort: 8080
      protocol: TCP
    env:
    - name: ENVIRONMENT
      valueFrom:
        fieldRef:
          fieldPath: metadata.labels['env']  # 动态注入环境变量
    - name: DB_HOST
      value: "db.production.svc.cluster.local"
    resources:
      requests:                    # 资源请求 (调度依据)
        cpu: "250m"
        memory: "512Mi"
      limits:                      # 资源限制 (防止资源耗尽)
        cpu: "1000m"
        memory: "1024Mi"
        ephemeral-storage: "2Gi"   # 磁盘使用限制
    livenessProbe:                # 存活探针
      httpGet:
        path: /healthz
        port: 8080
        httpHeaders:
        - name: Custom-Header
          value: "Liveness-Check"
      initialDelaySeconds: 15
      periodSeconds: 10
      timeoutSeconds: 3
      successThreshold: 1
      failureThreshold: 3
    readinessProbe:               # 就绪探针
      exec:
        command: ["/bin/sh", "-c", "curl -s http://localhost:8080/ready"]
      initialDelaySeconds: 5
      periodSeconds: 5
    startupProbe:                # 启动探针 (K8s 1.16+)
      httpGet:
        path: /startup
        port: 8080
      failureThreshold: 30       # 允许最长启动时间: 30*5=150秒
      periodSeconds: 5
    volumeMounts:
    - name: config-volume
      mountPath: /etc/web-app
      readOnly: true             # 只读挂载配置文件
    - name: data-volume
      mountPath: /var/data
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop: ["ALL"]           # 删除所有Linux Capabilities
      readOnlyRootFilesystem: true  # 只读根文件系统

  # Sidecar容器 (日志收集)
  - name: log-agent
    image: fluentd:1.14.6
    resources:
      requests:
        cpu: "100m"
        memory: "128Mi"
      limits:
        cpu: "200m"
        memory: "256Mi"
    volumeMounts:
    - name: data-volume
      mountPath: /var/log/web-app
    - name: fluentd-config
      mountPath: /etc/fluentd
      readOnly: true

  # 初始化容器 (前置检查)
  initContainers:
  - name: config-check
    image: busybox:1.34
    command: ['sh', '-c', 'test -f /etc/web-app/config.yaml && echo Config OK || exit 1']
    volumeMounts:
    - name: config-volume
      mountPath: /etc/web-app

  # 存储卷定义
  volumes:
  - name: config-volume
    configMap:
      name: web-app-config       # 使用ConfigMap管理配置
      items:
      - key: "config.yaml"
        path: "config.yaml"
  - name: fluentd-config
    configMap:
      name: fluentd-config-prod
  - name: data-volume
    persistentVolumeClaim:       # 持久化存储
      claimName: web-app-data-pvc
      readOnly: false

  # 其他配置
  serviceAccountName: web-app-sa  # 使用最小权限的ServiceAccount
  priorityClassName: high-priority  # 设置Pod调度优先级
  terminationGracePeriodSeconds: 60  # 优雅终止宽限期
  dnsConfig:                     # 定制DNS策略
    options:
    - name: ndots
      value: "2"

关键字段详解

1. apiVersionkind
  • apiVersion: v1
    表示使用Kubernetes核心API组的v1版本,Pod属于核心资源,无需指定其他API组(如apps/v1用于Deployment)。

  • kind: Pod
    声明资源类型为Pod(而非Deployment、Service等)。


2. metadata(元数据)
  • name: my-pod
    Pod的唯一标识符,同一命名空间内不可重复。

  • labels
    标签是键值对,用于资源分类和选择器匹配。例如:

    • Service通过selector匹配标签将流量路由到Pod。

    • kubectl get pods -l app=web 可过滤出带有app: web标签的Pod。


3. spec.containers(主容器配置)
  • name
    容器名称,Pod内唯一,用于日志查询和exec操作(如kubectl logs my-pod -c web-server)。

  • image
    容器镜像地址,支持Docker Hub、私有仓库等。格式为<仓库>/<镜像名>:<标签>,如nginx:latest

  • ports
    声明容器监听的端口(仅文档用途,实际网络暴露需通过Service或Ingress)。
    例如containerPort: 80表示容器内监听80端口。

  • resources
    资源请求和限制,防止资源竞争:

    • limits:容器最大可用资源,超过会被终止(OOMKilled)。

    • requests:容器启动所需最小资源(示例中未设置,但建议配置)。

    • 单位:

      • CPU:500m表示0.5核(1000m=1核)。

      • 内存:512Mi表示512MB(Gi表示GB)。

  • volumeMounts
    将存储卷挂载到容器内指定路径:

    • name对应volumes中的存储卷名称。

    • mountPath为容器内的挂载路径(如主容器将shared-data挂载到/var/log/nginx,Sidecar容器挂载到/var/log,实现日志共享)。


4. volumes(存储卷定义)
  • emptyDir: {}
    临时存储卷,生命周期与Pod一致。

    • Pod创建时自动创建,Pod删除时数据丢失。

    • 适用于临时文件共享或缓存。

    • 其他常用类型:

      • configMap:挂载配置文件。

      • persistentVolumeClaim:挂载持久化存储。


5. initContainers(初始化容器)
  • 执行顺序
    按定义顺序执行,全部成功后启动主容器。

  • 用途示例

    • 等待依赖服务(如数据库)就绪(如示例中的nslookup db-service)。

    • 预加载数据或配置文件。

    • 执行权限初始化(如修改文件系统权限)。

  • 与主容器的区别

    • 无就绪检查(Readiness Probe)。

    • 执行完成后立即终止,不会被重启。


YAML 示例的典型场景

  • 主容器 + Sidecar

    • web-server(Nginx)处理HTTP请求,日志写入/var/log/nginx

    • log-collector(Fluentd)从/var/log收集日志并发送至日志系统。

    • 通过共享的emptyDir卷实现日志文件传递。

  • 初始化依赖检查

    • init-db容器持续检查db-service是否可解析(即依赖服务是否就绪),避免主容器启动时连接失败。

注意事项 

  • 资源限制

           若未设置requests,Kubernetes默认requests=limits,可能导致资源分配不足。建议显式设置:

resources:
  requests:
    memory: "256Mi"
    cpu: "250m"
  limits:
    memory: "512Mi"
    cpu: "500m"
  • 临时存储风险

    • emptyDir数据非持久化,重要数据需使用persistentVolumeClaim

  • 标签管理

    • 合理使用标签(如appenvversion)便于资源筛选和管理。

  • Sidecar 容器协作

    • 确保Sidecar容器与主容器的生命周期一致,避免资源竞争。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值