编写Deployment、Service与Ingress的完整YAML并支持灰度

解读

在国内云原生面试中,这道题考察的是“把 Django 应用真正搬到线上”的闭环能力:

  1. 用 Deployment 声明式管理无状态 Pod,并给出可灰度的策略;
  2. 用 Service 解决集群内流量发现;
  3. 用 Ingress 暴露统一入口,并借助原生或 Nginx-Ingress 的灰度能力完成金丝雀/滚动灰度;
  4. 所有对象字段必须符合国内主流版本(1.20+),并体现“可落地”细节(镜像拉取密钥、探针、资源配额、HPA 预留、PDB、优雅终止等)。
    面试官常追问:灰度比例如何动态调整?回滚策略?标签如何设计才能兼容 CI/CD?因此 YAML 必须“一眼能改”,而不是 Demo 即弃。

知识点

  1. Deployment 的滚动更新策略:maxUnavailable、maxSurge、revisionHistoryLimit。
  2. Label 与 Selector 的“双标签”设计:稳定标签 app=web 区分产品,版本标签 version=stable/canary 区分灰度。
  3. Ingress-Nginx 的 Canary 注解:
    nginx.ingress.kubernetes.io/canary: "true"
    nginx.ingress.kubernetes.io/canary-weight: "10"
    国内阿里云 MSE、腾讯云 TCM 同理,只是注解前缀不同。
  4. Service 仅做四层负载,灰度流量由 Ingress-Controller 按 Header、Cookie 或权重分流;因此需要两个 Service(stable-svc、canary-svc)对应两套 Deployment。
  5. 镜像拉取密钥、安全上下文、优雅终止(lifecycle.preStop)、就绪探针(manage.py check --deploy)是生产必选项。
  6. 灰度与回滚:调整 Ingress 权重或替换 canary 镜像后,kubectl rollout undo deployment/django-canary 即可秒级回滚。

答案

以下 YAML 可直接 kubectl apply -f,默认命名空间为 django-prod,镜像使用国内阿里云 ACR 示例。
文件 1:stable-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: django-stable
  namespace: django-prod
  labels:
    app: web
    version: stable
spec:
  replicas: 3
  revisionHistoryLimit: 5
  selector:
    matchLabels:
      app: web
      version: stable
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: web
        version: stable
    spec:
      terminationGracePeriodSeconds: 30
      imagePullSecrets:
        - name: acr-secret
      containers:
        - name: django
          image: registry.cn-hangzhou.aliyuncs.com/demo/django:v1.0.0
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 8000
              name: http
          command: ["gunicorn", "config.wsgi:application", "-b", "0.0.0.0:8000", "-k", "uvicorn.workers.UvicornWorker", "--max-requests", "1000", "--max-requests-jitter", "100"]
          readinessProbe:
            httpGet:
              path: /health/
              port: http
            initialDelaySeconds: 5
            periodSeconds: 5
            successThreshold: 1
          livenessProbe:
            httpGet:
              path: /health/
              port: http
            initialDelaySeconds: 15
            periodSeconds: 10
          resources:
            requests:
              cpu: 200m
              memory: 256Mi
            limits:
              cpu: 1000m
              memory: 1Gi
          lifecycle:
            preStop:
              exec:
                command: ["/bin/sh", "-c", "sleep 10"]

文件 2:canary-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: django-canary
  namespace: django-prod
  labels:
    app: web
    version: canary
spec:
  replicas: 1
  revisionHistoryLimit: 2
  selector:
    matchLabels:
      app: web
      version: canary
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: web
        version: canary
    spec:
      terminationGracePeriodSeconds: 30
      imagePullSecrets:
        - name: acr-secret
      containers:
        - name: django
          image: registry.cn-hangzhou.aliyuncs.com/demo/django:v2.0.0
          imagePullPolicy: Always
          ports:
            - containerPort: 8000
              name: http
          command: ["gunicorn", "config.wsgi:application", "-b", "0.0.0.0:8000", "-k", "uvicorn.workers.UvicornWorker", "--max-requests", "1000", "--max-requests-jitter", "100"]
          readinessProbe:
            httpGet:
              path: /health/
              port: http
            initialDelaySeconds: 5
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /health/
              port: http
            initialDelaySeconds: 15
            periodSeconds: 10
          resources:
            requests:
              cpu: 200m
              memory: 256Mi
            limits:
              cpu: 1000m
              memory: 1Gi
          lifecycle:
            preStop:
              exec:
                command: ["/bin/sh", "-c", "sleep 10"]

文件 3:stable-service.yaml

apiVersion: v1
kind: Service
metadata:
  name: django-stable-svc
  namespace: django-prod
  labels:
    app: web
    version: stable
spec:
  type: ClusterIP
  selector:
    app: web
    version: stable
  ports:
    - name: http
      port: 80
      targetPort: http

文件 4:canary-service.yaml

apiVersion: v1
kind: Service
metadata:
  name: django-canary-svc
  namespace: django-prod
  labels:
    app: web
    version: canary
spec:
  type: ClusterIP
  selector:
    app: web
    version: canary
  ports:
    - name: http
      port: 80
      targetPort: http

文件 5:ingress.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: django-ingress
  namespace: django-prod
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/proxy-body-size: "20m"
    nginx.ingress.kubernetes.io/proxy-connect-timeout: "30"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "300"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "300"
spec:
  rules:
    - host: api.demo.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: django-stable-svc
                port:
                  name: http
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: django-canary-ingress
  namespace: django-prod
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/canary: "true"
    nginx.ingress.kubernetes.io/canary-weight: "10"
spec:
  rules:
    - host: api.demo.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: django-canary-svc
                port:
                  name: http

灰度步骤:

  1. 先 apply stable 三套 YAML,确保 v1.0.0 全流量;
  2. 修改 canary-deployment.yaml 中的镜像版本为 v2.0.0,apply;
  3. 调整 django-canary-ingress 的 canary-weight 从 10 逐步升到 100,观察 Prometheus 错误率;
  4. 若指标正常,将 stable 镜像改为 v2.0.0 并滚动升级,完成后删除 canary 相关对象,实现“全量发布”。

拓展思考

  1. 多集群灰度:华东集群全量,华北集群 10% 灰度,可结合 Ingress-Nginx 的 canary-by-header=Region 做更细粒度控制。
  2. 自动权重调整:基于 Flagger 或 Kruise-Rollout,在错误率 > 5% 或 P99 延迟 > 500 ms 时自动回滚,无需人工干预。
  3. 零中断发布:给 Django 加 /ready 接口,在 migrate 未完成时返回 503,防止流量进入未完成初始化的 Pod;同时配置 PodDisruptionBudget,保证发布期间最少可用副本数。
  4. 镜像加速:国内节点可替换 docker.io 为阿里云 ACR 镜像加速器,并在 DaemonSet 中预拉取基础镜像,减少冷启动时间。
  5. 安全加固:在 Deployment 中增加 securityContext.runAsNonRoot: true 与 readOnlyRootFilesystem: true,把静态文件与媒体目录挂到 emptyDir 或 OSS 卷,降低容器逃逸风险。