🎓 第25课:毕业项目——生产级K8s平台

📌 课程阶段:实战项目(5/5)|预计时间:120分钟|难度:⭐⭐⭐⭐⭐

一、项目目标

综合前24课所学,构建一个生产级K8s平台:多集群管理、GitOps交付、全链路可观测、安全合规、自动伸缩、容灾恢复。

┌─────────── 生产级K8s平台架构 ──────────┐
│                                          │
│  ┌──────────────────────────────────┐    │
│  │         平台门户 (Portal)         │    │
│  │  自助服务 / 多租户 / 审批流程      │    │
│  └──────────────┬───────────────────┘    │
│                 │                          │
│  ┌──────────────▼───────────────────┐    │
│  │       平台控制层                  │    │
│  │  ArgoCD | Karmada | OPA/Gatekeeper│   │
│  │  cert-manager | External Secrets  │   │
│  └──────────────┬───────────────────┘    │
│                 │                          │
│  ┌──────────────▼───────────────────┐    │
│  │     可观测层                      │    │
│  │  Prometheus + Grafana + Loki      │   │
│  │  Tempo(Trace) + Alertmanager      │   │
│  └──────────────┬───────────────────┘    │
│                 │                          │
│  ┌──────────────▼───────────────────┐    │
│  │     安全层                        │    │
│  │  RBAC | NetworkPolicy | mTLS      │   │
│  │  PodSecurity | Trivy Scanner      │   │
│  └──────────────┬───────────────────┘    │
│                 │                          │
│  ┌──────────────▼───────────────────┐    │
│  │     基础设施层                    │    │
│  │  多集群(C1/C2/C3) + Velero        │   │
│  │  GPU节点 | 存储类 | CNI(Cilium)   │   │
│  └──────────────────────────────────┘    │
│                                          │
│  贯穿原则:                              │
│  🔹 GitOps — 所有配置版本化              │
│  🔹 声明式 — 期望状态驱动               │
│  🔹 零信任 — 默认拒绝 + 最小权限        │
│  🔹 可观测 — 指标+日志+追踪三合一       │
│  🔹 弹性 — 自动伸缩 + 容灾恢复         │
└──────────────────────────────────────────┘

二、GitOps仓库结构

# 生产级GitOps仓库
platform-repo/
├── clusters/                    # 集群配置
│   ├── production/
│   │   ├── kustomization.yaml
│   │   ├── flux-system/         # Flux引导
│   │   └── infrastructure/      # 基础设施
│   │       ├── cert-manager/
│   │       ├── external-secrets/
│   │       ├── ingress-nginx/
│   │       ├── monitoring/
│   │       └── security/
│   ├── staging/
│   └── development/
├── infrastructure/              # 共享基础设施
│   ├── base/
│   │   ├── namespace.yaml
│   │   ├── rbac.yaml
│   │   └── networkpolicy.yaml
│   └── components/
│       ├── monitoring/          # ServiceMonitor模板
│       ├── security/            # OPA策略
│       └── storage/             # StorageClass
├── apps/                        # 应用清单
│   ├── base/                    # 基础Kustomize
│   │   ├── deployment.yaml
│   │   ├── service.yaml
│   │   └── kustomization.yaml
│   ├── overlays/
│   │   ├── production/          # 生产覆盖
│   │   ├── staging/             # 预发覆盖
│   │   └── development/        # 开发覆盖
│   └── platform-services/
│       ├── argocd/
│       ├── vault/
│       └── observability/
├── policies/                    # 策略即代码
│   ├── opa/
│   │   ├── no-latest-image.yaml
│   │   ├── require-resources.yaml
│   │   └── deny-privileged.yaml
│   └── network-policies/
│       ├── default-deny.yaml
│       └── allow-monitoring.yaml
└── scripts/
    ├── bootstrap.sh             # 集群初始化脚本
    ├── disaster-recovery.sh     # 容灾恢复
    └── rotate-secrets.sh        # 密钥轮换

三、OPA Gatekeeper策略

# 安装Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/release-3.15/deploy/gatekeeper.yaml

# ✅ 验证通过
kubectl get pods -n gatekeeper-system

# 策略1:禁止latest镜像
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8sallowedimages
spec:
  crd:
    spec:
      names:
        kind: K8sAllowedImages
      validation:
        openAPIV3Schema:
          type: object
          properties:
            repos:
              type: array
              items:
                type: string
  targets:
  - target: admission.k8s.gatekeeper.sh
    rego: |
      package k8sallowedimages
      violation[{"msg": msg}] {
        container := input.review.object.spec.containers[_]
        not startswith(container.image, input.parameters.repos[_])
        msg := sprintf("container <%v> has an invalid image repo <%v>, allowed repos are %v", [container.name, container.image, input.parameters.repos])
      }
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedImages
metadata:
  name: prod-repos-only
spec:
  match:
    kinds: [{apiGroups: [""], kinds: ["Pod"]}]
    namespaces: ["production"]
  parameters:
    repos:
    - "registry.example.com/"
    - "docker.io/bitnami/"

# 策略2:必须设置资源限制
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequiredresources
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredResources
  targets:
  - target: admission.k8s.gatekeeper.sh
    rego: |
      package k8srequiredresources
      violation[{"msg": msg}] {
        container := input.review.object.spec.containers[_]
        not container.resources.limits.cpu
        msg := sprintf("container <%v> must set cpu limits", [container.name])
      }
      violation[{"msg": msg}] {
        container := input.review.object.spec.containers[_]
        not container.resources.limits.memory
        msg := sprintf("container <%v> must set memory limits", [container.name])
      }
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredResources
metadata:
  name: require-limits
spec:
  match:
    kinds: [{apiGroups: ["apps"], kinds: ["Deployment"]}]

四、平台健康检查清单

检查项命令期望
节点状态kubectl get nodes所有Ready
Pod健康kubectl get pods -A \| grep -v Running无异常Pod
证书有效期kubeadm certs check-expiration未过期
etcd健康etcdctl endpoint health全部healthy
资源余量kubectl top nodesCPU<80%, Mem<85%
PVC容量kubectl get pv \| grep Bound未满
备份状态velero backup get最近备份Completed
安全策略kubectl get constraint无违规
证书签发kubectl get certificates全部Ready
告警状态amtool alert query无Critical告警

五、自动化健康检查脚本

#!/bin/bash
# platform-healthcheck.sh - 平台健康检查

set -euo pipefail

PASS=0; FAIL=0; WARN=0

check() {
  local name="$1" cmd="$2" expect="$3"
  result=$(eval "$cmd" 2>&1) || true
  if echo "$result" | grep -q "$expect"; then
    echo "✅ $name"
    ((PASS++))
  else
    echo "❌ $name: $result"
    ((FAIL++))
  fi
}

# 节点检查
check "所有节点Ready" \
  "kubectl get nodes -o jsonpath='{.items[*].status.conditions[?(@.type==\"Ready\")].status}'" \
  "True"

# Pod检查
crash_count=$(kubectl get pods -A --field-selector=status.phase!=Running,status.phase!=Succeeded 2>/dev/null | wc -l || echo "0")
if [ "$crash_count" -le 1 ]; then
  echo "✅ 无异常Pod"
  ((PASS++))
else
  echo "❌ 有 $((crash_count-1)) 个异常Pod"
  ((FAIL++))
fi

# etcd检查
check "etcd健康" \
  "ETCDCTL_API=3 etcdctl endpoint health --cluster 2>&1" \
  "healthy"

# 证书检查
check "K8s证书有效" \
  "sudo kubeadm certs check-expiration 2>&1" \
  "CERTIFICATE AUTHORITY"

# 备份检查
check "Velero备份正常" \
  "velero backup get --output json 2>&1" \
  "Completed"

# 告警检查
firing=$(kubectl get prometheusrule -A 2>/dev/null | wc -l || echo "0")
echo "⚠️ 检查Prometheus告警: $firing 条规则"

# 汇总
echo ""
echo "========== 健康检查汇总 =========="
echo "✅ 通过: $PASS"
echo "❌ 失败: $FAIL"
echo "⚠️  警告: $WARN"
echo "==================================="

[ "$FAIL" -gt 0 ] && exit 1 || exit 0

六、平台运维手册

# 生产级K8s平台运维手册

## 日常巡检(每日)
1. 检查节点状态:kubectl get nodes
2. 检查异常Pod:kubectl get pods -A | grep -v Running
3. 检查资源使用:kubectl top nodes
4. 检查告警:amtool alert query
5. 检查备份:velero backup get

## 周度维护
1. 证书有效期检查
2. etcd快照验证
3. PV容量检查
4. 安全策略合规扫描
5. 容灾演练(月度)

## 变更流程
1. 提交PR到GitOps仓库
2. ArgoCD自动检测变更
3. Staging环境验证
4. 人工审批→Production同步
5. 监控指标确认

## 应急响应
1. P0告警→5分钟响应
2. 影响评估→通知stakeholder
3. 故障定位→日志+指标+追踪
4. 修复执行→验证恢复
5. 复盘文档→24小时内

## 扩容流程
1. 触发条件:CPU>70%持续15分钟
2. HPA自动扩容Pod
3. Cluster Autoscaler扩容节点
4. 验证新节点就绪
5. 确认流量均衡

七、毕业项目清单

📋 生产级K8s平台建设清单

□ 1. 集群部署
  □ 高可用控制平面(3 Master)
  □ etcd集群(3节点+定期备份)
  □ Worker节点自动伸缩

□ 2. 网络与存储
  □ CNI(Cilium/Calico)+ NetworkPolicy
  □ StorageClass(SSD/HDD/NFS)
  □ CSI驱动配置

□ 3. 安全合规
  □ RBAC多租户隔离
  □ OPA Gatekeeper策略
  □ PodSecurity标准
  □ Secret加密+外部管理
  □ mTLS(Istio/Cilium)

□ 4. 可观测性
  □ Prometheus + Grafana监控
  □ Loki/ELK日志
  □ Tempo/Jaeger追踪
  □ Alertmanager告警

□ 5. CI/CD
  □ ArgoCD GitOps
  □ 金丝雀/蓝绿部署
  □ 镜像安全扫描

□ 6. 容灾
  □ Velero备份
  □ 多集群容灾
  □ 容灾演练

八、课程总结

25课从K8s基础到生产级平台,完整覆盖了:

阶段课程核心技能
K8s基础01-05架构+Pod+Deployment+Service+ConfigMap
存储调度06-10PV/PVC+调度+HPA+DaemonSet+Ingress
安全监控11-15RBAC+NetworkPolicy+Prometheus+日志+SLO
高级运维16-20Helm+CRD+Operator+多集群+容灾
实战项目21-25微服务+CI/CD+Istio+GPU+毕业项目

🏆🏆🏆 K8s实战课程毕业!

恭喜你完成了全部25课的学习!

持续学习方向:云原生安全(CNSP)、平台工程(Platform Engineering)、eBPF深度可观测、Serverless on K8s。

🚀 Go forth and orchestrate!