美文网首页
docker springboot项目镜像优化

docker springboot项目镜像优化

作者: 小猋_a8f1 | 来源:发表于2019-05-28 11:50 被阅读0次

    遇到的问题:
    公司java项目按老的方式打包出来一个fat jar,100MB, 推送到腾讯云镜像仓库很慢,8分钟。。。走的是公网,专线暂时还没配置好
    以前是内网harbor,速度还不明显。
    归根究底,一次推送100MB是个不合理的事情

    思路:

    1. 了解spring boot打包,期望将依赖的libs 和 业务代码拆分
    2. 优化dockerfile,充分利用缓存

    解决问题:

    1. 先修改spring-boot-maven-plugin,只打包业务代码。网上有些是配置exclude,我试了,恶心到了。。那么多包挨个找
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <!--<mainClass>cn.qg.clotho.Bootstrap</mainClass>-->
            <layout>ZIP</layout>
            <!--<executable>true</executable>-->
            <includes>
                <include>
                    <groupId>${project.groupId}</groupId>
                    <artifactId>${project.artifactId}</artifactId>
                </include>
            </includes>
        </configuration>
    </plugin>
    
    1. 新增maven-dependency-plugin,将依赖移到libs目录下
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
            <execution>
                <id>copy</id>
                <phase>package</phase>
                <goals>
                    <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                    <type>jar</type>
                    <includeTypes>jar</includeTypes>
                    <includeScope>runtime</includeScope>
                    <outputDirectory>${project.build.directory}/libs</outputDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>
    
    1. 优化dockerfile
      参考 https://medium.com/@nieldw/caching-maven-dependencies-in-a-docker-build-dca6ca7ad612 ,牛逼
    FROM mvn3.5 as builder
    WORKDIR /build
    COPY pom.xml .
    RUN mvn dependency:go-offline
    
    COPY src/ /build/src/
    RUN mvn package
    
    FROM jdk1.8
    EXPOSE 80
    CMD exec java -Dloader.path="/home/libs/" -jar /home/app.jar
    COPY --from=builder /build/target/*.jar /home/app.jar
    COPY --from=builder /build/target/libs /home/libs/
    

    搞定。最终代码变化每次推送也就1MB多
    启动命令 java -Dloader.path="libs/" -jar app.jar

    相关文章

      网友评论

          本文标题:docker springboot项目镜像优化

          本文链接:https://www.haomeiwen.com/subject/kzvrtctx.html