微服务Docker打包插件配置

SpringBoot打包插件配置

聚合工程 pom.xml 添加全局变量

  • 镜像前缀: image-prefix 自行修改
1
2
3
4
<properties>
<docker.image.prefix>image-prefix</docker.image.prefix>
</properties>

子模块 pom.xml 添加配置

  • 打包名称: alibaba-cloud-finalName 自行修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<build>
<finalName>alibaba-cloud-finalName</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>

<!--需要加这个, 不然打包镜像找不到启动文件-->
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>

<configuration>
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>

<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<configuration>
<repository>${docker.image.prefix}/${project.artifactId}</repository>
<buildArgs>
<JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
</buildArgs>
</configuration>
</plugin>
</plugins>
</build>

子模块 pom.xml 同级添加 Dockerfile 配置文件

1
2
3
4
5
FROM adoptopenjdk/openjdk11:ubi
VOLUME /tmp
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

docker镜像过大

  • 在 Dockerfile 中, 每一条指令都会创建一个镜像层, 会增加整体镜像的大小. 合并多个指令串起来执行, Dockerfile 中的 RUN 指令通过 &&/ 支持将命令串联在一起, 可以省不少镜像层

  • 选用更小的基础镜像, 比如运行 SpringCloud 项目,不必用 jdk , 直接选用 jre 镜像即可, 可以节省50%的内存甚至更多

优化后的 Dockerfile

1
2
3
4
5
FROM adoptopenjdk/openjdk11:jre11u-nightly
VOLUME /tmp
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

执行 console 控制台 maven 指令打包

配置编码格式 pom.xml

1
2
3
4
5
6
7
8
9
10
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
<encoding>utf8</encoding>
</configuration>
</plugin>

1
2
3
4
5
6
7
<properties>
<java.version>11</java.version>
<!--使用utf8构建, 不要用系统编码方式构建-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>

父模块执行 mvn

1
mvn clean install

子模块执行 mvn

1
mvn install '-Dmaven.test.skip=true' dockerfile:build