如何根据 Profile 选择不同基础镜像(distroless vs alpine)?

解读

在国内企业级 CI/CD 流水线里,镜像体积与攻击面直接决定安全评审能否通过,镜像拉取速度又决定发布窗口能否守住。面试官问“用 Maven 怎么切镜像”,核心是想确认两点:

  1. 你是否理解 Spring Boot 插件的 build-image 目标 与 jib-maven-plugin 两种主流打法;
  2. 你是否能把 Profile + 属性注入 + 插件配置 做成“零脚本”切换,而不是写死 Dockerfile 再让运维手动改。
    答“写两个 Dockerfile”只能拿 60 分;答“用 Maven Profile 动态传参”才算摸到 90 分门槛。

知识点

  1. Maven Profile 的激活方式:命令行 -P、系统属性 -D、CI 环境变量、settings.xml 里 activeByDefault。
  2. 属性优先级:profile 内定义 > 命令行 -D > project.properties > settings.xml,同名属性后者不会覆盖前者。
  3. Spring Boot 2.7+ 的 build-image 目标:底层用 Paketo Buildpacks,通过 -Dspring-boot.build-image.builder 或 <image><builder> 节点即可换 builder;而 builder 里已打包 distroless 或 alpine 的 run 镜像。
  4. Google jib-maven-plugin 3.3+:<from><image> 节点支持占位符 ${jib.base.image},与 Profile 搭配最直观;同时支持 <platform><architecture> 指定 amd64/arm64,满足国内云厂商多架构计费需求。
  5. CI 最佳实践:GitLab-CI 的 variables: 里声明 BASE_IMAGE: "distroless",Maven 命令 mvn -PPROFILEcleanpackage−Djib.base.image=PROFILE clean package -Djib.base.image=BASE_IMAGE,一条指令完成镜像切换,无需改 pom。
  6. 镜像安全基线:国内金融、运营商要求 distroless 镜像 ≤ 80 MB、alpine 镜像 ≤ 60 MB,且必须通过 trivy 0 高危漏洞扫描;Profile 里可再挂 trivy-maven-plugin 做门禁。

答案

我采用 “Profile + 属性 + 插件三元组” 方案,零 Dockerfile,一条命令切换。以 jib-maven-plugin 为例,pom 核心片段如下:

<profiles> <!-- 默认 distroless,面向生产 --> <profile> <id>prod</id> <activation><activeByDefault>true</activeByDefault></activation> <properties> <jib.base.image>gcr.io/distroless/java17-debian12:nonroot</jib.base.image> </properties> </profile> <!-- 研发、调试场景用 alpine,方便 apk add --> <profile> <id>dev</id> <properties> <jib.base.image>eclipse-temurin:17-jre-alpine</jib.base.image> </properties> </profile> </profiles> <plugin> <groupId>com.google.cloud.tools</groupId> <artifactId>jib-maven-plugin</artifactId> <version>3.4.0</version> <configuration> <from> <!-- 关键占位符,由 Profile 注入 --> <image>${jib.base.image}</image> </from> <to> <image>harbor.example.com/demo/${project.artifactId}:${project.version}</image> <auth> <username>${harbor.user}</username> <password>${harbor.pass}</password> </auth> </to> <container> <mainClass>com.example.Application</mainClass> <user>nobody</user> </container> </configuration> </plugin>

使用方式:

  • 打生产包:mvn -Pprod clean compile jib:build
  • 打开发包:mvn -Pdev clean compile jib:dockerBuild(本地 Docker 守护进程调试)

若项目强制 Spring Boot build-image,也可把 builder 镜像地址抽成属性,<spring-boot.build-image.builder>${paketo.builder}</spring-boot.build-image.builder>,原理完全一致。

拓展思考

  1. 多架构合并:在 CI 里并行 mvn -Pprod -Djib.base.image=gcr.io/distroless/java17-debian12:nonroot -Djib.platform=linux/amd64 与 linux/arm64,最后 docker manifest create 统一镜像,一份 Dockerfile 都不用写即可交付多架构镜像,满足国内云厂商“按需计费”要求。
  2. 安全左移:在 distroless Profile 里再挂 trivy-maven-plugin,build 阶段若扫出高危则直接失败,把“镜像安全”从运维环节左移到开发阶段,符合国内监管“三同步”原则。
  3. 镜像缓存加速:把 alpine 镜像推到 阿里云 ACR 的加速域名,在 Profile 里定义 jib.base.image=registry.cn-hangzhou.aliyuncs.com/distroless/java17:nonroot,CI 节点走内网拉取,5 秒完成基础镜像准备,彻底解决“国外仓库抽风”导致的构建超时问题。