Docker制作SpringBoot镜像

2021-05-28  本文已影响0人  茶还是咖啡

确保您的SpringBoot版本为2.3.0-RELEASE及以上


编写一个简单的controller

@RequestMapping("hello")
@RestController
public class OneController {

    @GetMapping
    public Object hello(){
        return "Hello";
    }
}

1.resources资源路径下新建Dockerfile

# 指定基础镜像,这是分阶段构建的前期阶段
FROM openjdk:8 as builder
# 执行工作目录
WORKDIR application
# 配置参数
ARG JAR_FILE=./*.jar
# 将编译构建得到的jar文件复制到镜像空间中
COPY ${JAR_FILE} application.jar
# 通过工具spring-boot-jarmode-layertools从application.jar中提取拆分后的构建结果
RUN java -Djarmode=layertools -jar application.jar extract

# 正式构建镜像
FROM openjdk:8
WORKDIR application
# 前一阶段从jar中提取除了多个文件,这里分别执行COPY命令复制到镜像空间中,每次COPY都是一个layer
COPY --from=builder application/dependencies/ ./
COPY --from=builder application/spring-boot-loader/ ./
COPY --from=builder application/snapshot-dependencies/ ./
COPY --from=builder application/application/ ./
# 直接指定运行的main方法
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]
  1. maven配置文件中加入docker插件
    <properties>
        <docker.image.prefix>registry.aliyuncs.com/test</docker.image.prefix>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                    <!--docker文件所在的目录-->
                    <dockerDirectory>src/main/resources</dockerDirectory>
                    <imageTags>1.1.0</imageTags>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>
  1. 打包镜像
mvn clean package -Dmaven.test.skip=true docker:build
  1. 查看镜像
  1. 运行镜像


上一篇下一篇

猜你喜欢

热点阅读