如何在 `mvn package` 时生成 `Dockerfile.dev` 与 `Dockerfile.prod`?
解读
面试官真正想考察的是“把构建产物与部署描述一起版本化”的能力。国内大厂普遍要求“一次编译,随处部署”,而 Dockerfile 随包产出正是落地这一原则的关键环节。
回答时要体现三点:
- 生命周期钩子:必须绑定到
package之后、install之前,保证产物与 Dockerfile 同时出现。 - 区分环境:通过 Maven Profile 或
maven.resource.filtering动态注入变量,避免硬编码。 - 无侵入:不改动业务代码,只用官方插件完成,体现“约定优于配置”的 Maven 哲学。
知识点
- maven-antrun-plugin:最轻量,直接写
<echo file="target/Dockerfile.dev">…</echo>,但可读性差。 - maven-assembly-plugin:适合把 Dockerfile 当成普通文件打进 zip/tar,但不能动态渲染变量。
- maven-resources-plugin + filtering:把
src/main/docker/Dockerfile.dev当成模板,通过${}占位符注入版本、JAR 名称,国内项目最常用。 - io.fabric8:docker-maven-plugin:一步到位生成并构建镜像,但太重,很多公司只要求产出文件,CI 系统再负责 build。
- spring-boot-maven-plugin 的 build-image:只能生成 OCI 镜像,无法输出 Dockerfile,不符合题意。
答案
推荐用 maven-resources-plugin 绑定到 package 阶段,配合 Profile 区分环境,零依赖、零脚本,CI/CD 友好。
在父 POM 或当前模块 POM 中加入:
<profiles>
<profile>
<id>dev</id>
<properties>
<dockerfile.name>Dockerfile.dev</dockerfile.name>
<base.image>openjdk:17-jdk-slim</base.image>
<profile.suffix>dev</profile.suffix>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<dockerfile.name>Dockerfile.prod</dockerfile.name>
<base.image>registry.cn-hangzhou.aliyuncs.com/company/openjdk:17-jre-alpine</base.image>
<profile.suffix>prod</profile.suffix>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.1</version>
<executions>
<execution>
<id>generate-dockerfile</id>
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
<resources>
<resource>
<directory>src/main/docker</directory>
<includes>
<include>${dockerfile.name}</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
在 src/main/docker 放置模板文件 Dockerfile.dev 与 Dockerfile.prod,内容示例:
FROM ${base.image}
COPY ${project.build.finalName}.jar /app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]
执行
mvn clean package -Pdev
会在 target/ 下得到 已渲染变量的 Dockerfile.dev,同理 -Pprod 得到 Dockerfile.prod。
CI 系统只需 cat target/Dockerfile.* 即可继续构建镜像,无需二次渲染。
拓展思考
- 多模块场景:在父 POM 用
pluginManagement统一定义,子模块按需激活 Profile,避免每个子模块重复拷贝模板。 - 版本一致性:把
${project.version}写进镜像 tag,配合maven.build.timestamp实现“可追踪的镜像版本”,满足国内审计要求。 - 安全合规:在
Dockerfile.prod模板里加入RUN addgroup -g 1000 app && adduser -u 1000 -G app -s /bin/sh -D app强制非 root 启动,通过资源过滤开关控制,审计时直接查看 target 产物即可。 - 与 GitLab CI 联动:
.gitlab-ci.yml里只需docker build -f target/Dockerfile.prod -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA .,无需再写 sed 替换,降低脚本复杂度,体现 Maven 作为企业级标准的价值。