构建SpringBoot应用Docker镜像

准备工作

使用到的工具及运行环境:

  • JDK 1.8 及以上
  • Gradle 4+ 或 Maven 3.2+
  • 开发工具
    • Spring Tool Suite (STS)
    • IntelliJ IDEA
创建SpringBoot应用

这边我是使用 IntelliJ IDEA 创建的,你也可以通过这种方式创建然后导入到IDE中 http://start.spring.io/

在 pom.xml 中添加 docker maven插件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xumiao</groupId>
    <artifactId>spring-boot-docker</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-docker</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <docker.image.prefix>springio</docker.image.prefix>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!--build docker image-->
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>dockerfile-maven-plugin</artifactId>
                <version>1.4.9</version>
                <configuration>
                    <repository>${docker.image.prefix}/${project.artifactId}</repository>
                </configuration>
            </plugin>
            <!-- tag::unpack[] -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>unpack</id>
                        <phase>package</phase>
                        <goals>
                            <goal>unpack</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>${project.groupId}</groupId>
                                    <artifactId>${project.artifactId}</artifactId>
                                    <version>${project.version}</version>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!-- end::unpack[] -->
        </plugins>
    </build>

</project>

在 SpringBootApplication 启动文件中添加个简单的路由:

@SpringBootApplication
@RestController
public class Application {

    @RequestMapping("/")
    public String home() {
        return "Hello Docker World";
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
编写Dockerfile

在项目根目录创建 Dockerfile 文件,内容如下,启动类名全路径根据实际情况填写

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ARG DEPENDENCY=target/dependency
COPY ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY ${DEPENDENCY}/META-INF /app/META-INF
COPY ${DEPENDENCY}/BOOT-INF/classes /app
ENTRYPOINT ["java","-cp","app:app/lib/*","com.xumiao.springboot.docker.Application"]

FROM:基于openjdk镜像进行构建;第一条指令必须为FROM 指令。并且,如果在同一个Dockerfile中创建多个镜像时,可以使用多个FROM 指令(每个镜像一次)。

VOLUME: 指向了一个 /tmp 的目录,由于 SpringBoot 使用内置的Tomcat容器,Tomcat 默认使用 /tmp 作为工作目录。效果就是在主机的 /var/lib/docker 目录下创建了一个临时文件,并连接到容器的/tmp;如果应用中有对文件系统进行写操作这个是必须要写的。

ARG:设置构建参数

COPY:复制本地主机的 (为 Dockerfile 所在目录的相对路径)到容器中的 app 目录下

ENTRYPOINT:配置容器启动后执行的命令,并且不可被 docker run 提供的参数覆盖。每个 Dockerfile 中只能有一个 ENTRYPOINT ,当指定多个时,只有最后一个起效。

上面命令参考以下资料

https://jiajially.gitbooks.io/dockerguide/content/chapter_fastlearn/dockerfile_details.html
https://yeasy.gitbooks.io/docker_practice/image/dockerfile/

构建 Docker 镜像

启动 Docker 后在应用下目录执行以下 maven 命令开始构建

 mvn install dockerfile:build

执行完成后我们查看下构建好的 docker 镜像(docker image ps),如下:

springio/spring-boot-docker   latest              436d7666f2f3        About a minute ago   122MB
openjdk                       8-jdk-alpine        a3562aa0b991        5 months ago         105MB
运行 Docker 镜像

通过以下命令创建 docker 容器并运行:

docker run -p 8080:8080 -t springio/spring-boot-docker

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.9.RELEASE)

2019-10-24 13:33:09.064  INFO 1 --- [           main] c.xumiao.springboot.docker.Application   : Starting Application on 9a8a14b6d1ec with PID 1 (/app started by root in /)
2019-10-24 13:33:09.067  INFO 1 --- [           main] c.xumiao.springboot.docker.Application   : No active profile set, falling back to default profiles: default
2019-10-24 13:33:10.335  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-10-24 13:33:10.374  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-10-24 13:33:10.374  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.26]
2019-10-24 13:33:10.525  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-10-24 13:33:10.525  INFO 1 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1384 ms
2019-10-24 13:33:10.723  INFO 1 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-10-24 13:33:10.883  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-10-24 13:33:10.886  INFO 1 --- [           main] c.xumiao.springboot.docker.Application   : Started Application in 2.279 seconds (JVM running for 2.619)

我们通过docker ps查看一下容器运行情况:

docker ps

CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS                    NAMES
9a8a14b6d1ec        springio/spring-boot-docker   "java -cp app:app/li…"   4 minutes ago       Up 4 minutes        0.0.0.0:8080->8080/tcp   elegant_goldwasser

接着在浏览器访问http://localhost:8080可以看到“Hello Docker World”结果,大功告成!

参考资料

https://spring.io/guides/gs/spring-boot-Docker/

https://lw900925.github.io/docker/docker-springboot.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值