# apiVersion: 使用的 Kubernetes API 版本
# 不同资源类型使用不同的 apiVersion,Deployment 在 apps/v1 中稳定
apiVersion: apps/v1

# kind: 资源类型,可以是 Deployment、Service、ConfigMap、Pod 等
kind: Deployment

# metadata: 资源的元数据,用于唯一标识该对象
metadata:
  # name: Deployment 的名称,在命名空间内必须唯一
  name: my-nginx-deployment
  # namespace: 指定资源所属的命名空间,默认为 default
  namespace: default
  # labels: 自定义标签,键值对形式,用于组织和选择资源
  labels:
    app: nginx
    tier: frontend
  # annotations: 注解,与 labels 类似,但通常用于存储非标识性的元数据
  annotations:
    description: "This is my nginx deployment example"

# spec: 期望的状态描述,Deployment 的核心部分
spec:
  # replicas: 期望运行的 Pod 副本数量
  replicas: 3

  # selector: 定义 Deployment 如何找到要管理的 Pod
  # 必须与 Pod 模板中的标签匹配,支持两种方式:
  selector:
    # matchLabels: 简单的基于等值匹配的标签选择器
    matchLabels:
      app: nginx
    # matchExpressions: 更复杂的表达式选择器(可选)
    # matchExpressions:
    #   - key: tier
    #     operator: In          # 操作符: In, NotIn, Exists, DoesNotExist
    #     values: ["frontend"]

  # template: Pod 模板,用于定义要创建的 Pod 的细节
  template:
    metadata:
      # labels: Pod 的标签,必须与 selector.matchLabels 匹配
      labels:
        app: nginx
        tier: frontend
      # annotations: Pod 的注解(可选)
      annotations:
        prometheus.io/scrape: "true"
    # spec: Pod 的规格,定义 Pod 内容器的行为
    spec:
      # containers: 容器列表(可以定义多个容器)
      containers:
      # 第一个容器的配置
      - name: nginx-container                 # 容器名称
        image: nginx:1.21                      # 容器镜像及标签
        imagePullPolicy: IfNotPresent          # 镜像拉取策略:Always, Never, IfNotPresent
        # ports: 容器暴露的端口列表
        ports:
        - name: http                           # 端口名称,可在 service 中引用
          containerPort: 80                     # 容器监听的端口
          protocol: TCP                          # 协议:TCP 或 UDP
        # env: 环境变量设置
        env:
        - name: ENV_VAR_NAME                    # 环境变量名
          value: "some-value"                    # 直接赋值
        - name: DATABASE_HOST
          valueFrom:                             # 从其他来源获取值
            configMapKeyRef:                      # 从 ConfigMap 中获取
              name: app-config                     # ConfigMap 名称
              key: database.host                    # ConfigMap 中的键名
        - name: DATABASE_PASSWORD
          valueFrom:
            secretKeyRef:                          # 从 Secret 中获取
              name: db-secret                        # Secret 名称
              key: password                           # Secret 中的键名
        # envFrom: 批量导入环境变量(如整个 ConfigMap 或 Secret)
        envFrom:
        - configMapRef:
            name: app-config                        # 将 ConfigMap 中所有键值对导入为环境变量
        - secretRef:
            name: db-secret                          # 将 Secret 中所有键值对导入为环境变量
        # resources: 资源请求和限制
        resources:
          requests:                                # 容器启动时请求的资源(调度依据)
            memory: "64Mi"                          # 内存请求
            cpu: "250m"                              # CPU 请求,250m 表示 0.25 个核心
          limits:                                  # 容器可以使用的资源上限
            memory: "128Mi"
            cpu: "500m"
        # volumeMounts: 将存储卷挂载到容器中
        volumeMounts:
        - name: config-volume                      # 引用的卷名称(需在 volumes 中定义)
          mountPath: /etc/nginx/conf.d              # 容器内的挂载路径
          readOnly: true                             # 是否只读
        - name: data-volume
          mountPath: /var/log/nginx
        # livenessProbe: 存活探针,检查容器是否健康,失败则重启
        livenessProbe:
          httpGet:                                 # HTTP GET 请求方式
            path: /healthz                           # 请求路径
            port: 80                                  # 请求端口
            httpHeaders:                             # 可选,添加请求头
            - name: Custom-Header
              value: Awesome
          initialDelaySeconds: 15                   # 容器启动后延迟多少秒开始探测
          periodSeconds: 10                          # 探测间隔(秒)
          timeoutSeconds: 2                           # 探测超时时间
          failureThreshold: 3                         # 连续失败多少次视为不健康
          successThreshold: 1                         # 连续成功多少次视为健康(存活探针通常为 1)
        # readinessProbe: 就绪探针,检查容器是否准备好接收流量
        readinessProbe:
          httpGet:
            path: /ready
            port: 80
          initialDelaySeconds: 5
          periodSeconds: 5
        # startupProbe: 启动探针(用于慢启动容器),成功后由存活探针接管
        startupProbe:
          httpGet:
            path: /healthz
            port: 80
          failureThreshold: 30                       # 允许失败次数多(例如 30 * 10s = 300s)
          periodSeconds: 10
        # lifecycle: 生命周期钩子
        lifecycle:
          postStart:                                 # 容器启动后立即执行(不保证在 entrypoint 之前)
            exec:
              command: ["/bin/sh", "-c", "echo Container started"]
          preStop:                                   # 容器停止前执行(用于优雅终止)
            exec:
              command: ["/bin/sh", "-c", "nginx -s quit"]
        # command 和 args: 覆盖镜像的 entrypoint 和 cmd
        command: ["nginx"]                           # 可执行命令
        args: ["-g", "daemon off;"]                  # 传递给命令的参数
        # workingDir: 容器的工作目录
        workingDir: /usr/share/nginx/html
        # securityContext: 容器级别的安全设置
        securityContext:
          runAsUser: 1000                             # 以指定 UID 运行
          runAsNonRoot: true                          # 禁止以 root 运行
          capabilities:                               # Linux Capabilities
            drop: ["ALL"]                              # 删除所有权限
            add: ["NET_BIND_SERVICE"]                  # 添加绑定低端口的能力
          readOnlyRootFilesystem: true                 # 根文件系统只读
      # 第二个容器(示例,比如 sidecar 容器)
      - name: sidecar-container
        image: alpine:latest
        command: ["/bin/sh", "-c", "while true; do echo sidecar; sleep 30; done"]

      # volumes: 定义 Pod 级别的存储卷,供容器通过 volumeMounts 挂载
      volumes:
      - name: config-volume                           # 卷名称,与 volumeMounts.name 对应
        configMap:                                    # 基于 ConfigMap 的卷
          name: app-config                              # ConfigMap 名称
          items:                                        # 可选,指定要暴露的文件
          - key: nginx.conf                              # ConfigMap 中的键名
            path: default.conf                           # 在卷中的文件名
      - name: data-volume
        emptyDir: {}                                   # 临时空目录,随 Pod 生命周期
      - name: secret-volume
        secret:                                        # 基于 Secret 的卷
          secretName: db-secret
      - name: hostpath-volume
        hostPath:                                      # 挂载主机目录(一般不推荐)
          path: /var/log/nginx
          type: DirectoryOrCreate                       # 类型:DirectoryOrCreate, File, Socket 等
      - name: pvc-volume
        persistentVolumeClaim:                         # 基于持久卷声明(PVC)
          claimName: my-pvc                              # PVC 名称

      # nodeSelector: 将 Pod 调度到包含指定标签的节点上
      nodeSelector:
        disktype: ssd

      # tolerations: 容忍度,允许 Pod 调度到带有特定污点(taints)的节点
      tolerations:
      - key: "key1"
        operator: "Equal"          # Equal 或 Exists
        value: "value1"
        effect: "NoSchedule"       # NoSchedule, PreferNoSchedule, NoExecute
        tolerationSeconds: 3600     # 当 effect 为 NoExecute 时,指定可容忍的时间

      # affinity: 亲和性,更灵活地控制 Pod 调度
      affinity:
        nodeAffinity:                                   # 节点亲和性
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/hostname
                operator: In
                values:
                - node1
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            preference:
              matchExpressions:
              - key: disktype
                operator: In
                values:
                - ssd
        podAffinity:                                    # Pod 亲和性
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - cache
            topologyKey: "kubernetes.io/hostname"
        podAntiAffinity:                                # Pod 反亲和性(分散运行)
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: app
                  operator: In
                  values:
                  - nginx
              topologyKey: "kubernetes.io/hostname"

      # serviceAccountName: 指定 Pod 使用的 ServiceAccount
      serviceAccountName: my-service-account

      # automountServiceAccountToken: 是否自动挂载 ServiceAccount 的 API 令牌(默认 true)
      automountServiceAccountToken: true

      # restartPolicy: Pod 重启策略,仅适用于 Pod 级别(Deployment 中 Pod 通常使用 Always)
      restartPolicy: Always          # Always, OnFailure, Never

      # terminationGracePeriodSeconds: 优雅终止宽限期(秒),超过后强制终止
      terminationGracePeriodSeconds: 30

      # imagePullSecrets: 用于拉取私有镜像的凭证
      imagePullSecrets:
      - name: regcred

      # hostNetwork: 是否使用主机网络(默认 false)
      hostNetwork: false

      # dnsPolicy: DNS 策略
      dnsPolicy: ClusterFirst        # ClusterFirst, Default, None, ClusterFirstWithHostNet

      # dnsConfig: 自定义 DNS 配置(当 dnsPolicy 为 None 或 ClusterFirst 时可用)
      dnsConfig:
        nameservers:
        - 8.8.8.8
        searches:
        - ns1.svc.cluster.local
        options:
        - name: ndots
          value: "5"

      # securityContext: Pod 级别的安全上下文
      securityContext:
        runAsUser: 1000
        runAsGroup: 3000
        fsGroup: 2000                # 卷的所有组
        supplementalGroups: [4000]   # 附加组
        seLinuxOptions:
          level: "s0:c123,c456"

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐