如何打包为 Knative 容器?

解读

在国内云原生面试中,“Spring 应用如何跑在 Knative 上” 几乎成了标配题。面试官想确认三件事:

  1. 你是否真的把 Spring Boot 做成**“可容器化”**的制品,而不是简单打个 fat jar;
  2. 你是否理解 Knative 对容器**“冷启动友好”**的硬性要求(镜像体积、启动速度、探针协议);
  3. 你是否能把 CI/CD、镜像仓库、国内网络加速等**“落地细节”**讲清楚,而不是背官网文档。
    回答时务必围绕“镜像构建 → 启动优化 → Knative 描述文件 → 灰度发布”四步展开,每步给出可验证的命令或配置片段,体现工程化思维。

知识点

  • Spring Boot 2.5+ 的 layered jar 与 Cloud Native Buildpacks(CNB)
  • Docker Buildx 与 阿里云 ACR 缓存加速
  • -Dspring.profiles.active=prod 等 JVM 参数调优,包括 -XX:MaxRAMPercentage=70.0 与 -Xverify:none
  • Knative Serving 的 Container Conformance:必须监听 $PORT(默认 8080),提供 /health 和 /ready 端点
  • Startup Probe 与 Readiness Probe 的区别,以及 knative.dev/rollout-duration 注解做灰度
  • 国内镜像源:maven.aliyun.com、registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.9
  • 安全合规:镜像内禁止 root、使用 distroless 或 bellsoft/liberica-runtime-container:jre-17-slim
  • CI/CD:GitHub Actions + 阿里云 ACR EE 企业版 触发器,或 Jenkins + 阿里云 OSS 缓存 实现分层构建

答案

  1. 代码改造
    在 pom.xml 中启用 layered jar 并固定端口:

    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <configuration>
        <layers><enabled>true</enabled></layers>
      </configuration>
    </plugin>
    

    新增 KnativeProbeController 暴露 /health 与 /ready,返回 {"status":"UP"},状态码必须是 200。

  2. 镜像构建(国内加速)
    使用 Paketo Buildpacks 无需写 Dockerfile,一条命令:

    mvn spring-boot:build-image \
      -Dspring-boot.build-image.imageName=registry.cn-hangzhou.aliyuncs.com/your-company/app:1.0.0 \
      -Dspring-boot.build-image.builder=paketobuildpacks/builder-jammy-base:latest \
      -Dspring-boot.build-image.env.BPE_DELIM_JAVA_TOOL_OPTIONS=" " \
      -Dspring-boot.build-image.env.BPE_APPEND_JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=70.0 -Xverify:none -Dspring.profiles.active=prod"
    

    构建完成后自动推送到 阿里云杭州镜像仓库,layer 缓存命中率高,后续构建 10 秒内完成。

  3. Knative 描述文件
    创建 service.yaml,关键字段如下:

    apiVersion: serving.knative.dev/v1
    kind: Service
    metadata:
      name: spring-knative
      annotations:
        knative.dev/rollout-duration: "120s"
    spec:
      template:
        metadata:
          annotations:
            autoscaling.knative.dev/target: "100"
            autoscaling.knative.dev/scale-to-zero-grace-period: "30s"
        spec:
          containers:
          - image: registry.cn-hangzhou.aliyuncs.com/your-company/app:1.0.0
            ports:
            - containerPort: 8080
            env:
            - name: SERVER_PORT
              value: "8080"
            readinessProbe:
              httpGet:
                path: /ready
                port: 8080
              initialDelaySeconds: 0
              periodSeconds: 5
            startupProbe:
              httpGet:
                path: /health
                port: 8080
              initialDelaySeconds: 0
              periodSeconds: 3
              failureThreshold: 30
    

    应用配置:

    kubectl apply -f service.yaml
    
  4. 验证与灰度
    执行 kn service describe spring-knative 确认 Latest Ready Revision 为 spring-knative-00002;
    通过 curl -H "Knative-Tag: spring-knative-00001" http://spring-knative.default.example.com 做金丝雀验证;
    最后 kn service update spring-knative --traffic spring-knative-00002=100 --traffic spring-knative-00001=0 完成全量切换。

拓展思考

  • 冷启动瓶颈:如果 QPS 突发,镜像仍过大,可进一步用 GraalVM native-image 把启动时间压到 50 ms 以内,但需处理 Spring Native 的反射配置;国内可基于 阿里云函数计算 Custom Runtime 体验 Serverless Spring。
  • 配置漂移:Knative 支持 ConfigMap 热更新,但 Spring Boot 默认不感知,需要引入 spring-cloud-kubernetes-fabric8-config 做动态刷新,避免重启 Pod。
  • 多环境隔离:在阿里 ACK 集群中,用 Knative + OAM 模式,把 “镜像 tag” 作为 ApplicationConfiguration 的变量,一条 Git commit 触发 “dev → staging → prod” 三级流水线,零人工干预。
  • 安全加固:镜像推送到 ACR EE 实例后,开启 “镜像扫描+策略阻断”,禁止 CVE≥HIGH 的镜像被 Knative 拉取;同时配合 Gatekeeper 模板强制容器 runAsNonRoot=true,满足国内金融客户合规审计。