使用 Testcontainer 和 Docker 的 Spring Boot 开发模式


在本文中,您将学习如何使用 Spring Boot 对 Testcontainers 和 Docker Compose 的内置支持,以开发模式运行外部服务。Spring Boot 在当前最新版本3.1中引入了这些特性。

当然,您已经可以在 Spring Boot 应用程序测试中利用 Testcontainers。然而,在应用程序启动时运行外部数据库、消息代理或其他外部服务的能力是我一直在等待的。

特别是,由于竞争框架 Quarkus 已经提供了一个名为Dev Services 的类似功能,这在我的开发过程中非常有用。

此外,我们不应忘记另一个令人兴奋的功能——与 Docker Compose 的集成。

源代码
如果您想自己尝试,可以随时查看我的源代码。由于我经常使用 Testcontainer,您可以在我的几个存储库中找到示例。这是我们今天将使用的存储库列表:


您可以克隆它们,然后按照我的说明了解如何在开发模式下利用 Spring Boot 对 Testcontainers 和 Docker Compose 的内置支持。


使用 Spring Boot 支持 Docker Compose
从 3.1 版开始,Spring Boot 提供了对 Docker Compose 的内置支持。

假设我们包含以下 Maven 依赖项,Spring Boot 会在当前工作目录中查找 Docker Compose 配置文件。让我们仅为特定的 Maven 配置文件激活该机制:

<profiles>
  <profile>
    <id>compose</id>
    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-docker-compose</artifactId>
        <optional>true</optional>
      </dependency>
    </dependencies>
  </profile>
</profiles>


我们的目标是在运行应用程序之前运行所有必需的外部服务:
customer-service服务可以连接到 Mongo、Eureka,并调用account-service. 

我们需要准备docker-compose.yml和所有需要的容器定义。正如你所看到的,有mongo服务和两个应用程序discovery-service和account-service,它们使用本地Docker镜像。

version: "3.8"
services:
  mongo:
    image: mongo:5.0
    ports:
      - "27017:27017"
  discovery-service:
    image: sample-spring-microservices-advanced/discovery-service:1.0-SNAPSHOT
    ports:
      - "8761:8761"
    healthcheck:
      test: curl --fail http://localhost:8761/eureka/v2/apps || exit 1
      interval: 4s
      timeout: 2s
      retries: 3
    environment:
      SPRING_PROFILES_ACTIVE: docker
  account-service:
    image: sample-spring-microservices-advanced/account-service:1.0-SNAPSHOT
    ports:
      - "8080"
    depends_on:
      discovery-service:
        condition: service_healthy
    links:
      - mongo
      - discovery-service
    environment:
      SPRING_PROFILES_ACTIVE: docker


在我们运行服务之前,让我们用我们的应用程序构建镜像。我们也可以使用基于Buildpacks的内置Spring Boot机制,但我有一些问题。在我的情况下,Jib工作得很好。

<profile>
  <id>build-image</id>
  <build>
    <plugins>
      <plugin>
        <groupId>com.google.cloud.tools</groupId>
        <artifactId>jib-maven-plugin</artifactId>
        <version>3.3.2</version>
        <configuration>
          <to>
            <image>sample-spring-microservices-advanced/${project.artifactId}:${project.version}</image>
          </to>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>dockerBuild</goal>
            </goals>
            <phase>package</phase>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

让我们在版本库根目录下执行以下命令:

$ mvn clean package -Pbuild-image -DskipTests

构建成功后,我们可以用docker images命令验证可用的镜像列表。

最后的思考
Spring Boot 3.1在容器化方面有多项改进。特别是与开发中与应用一起运行Testcontainers的能力有关的功能,是我所期待的。我希望这篇文章能阐明你如何利用Spring Boot的最新功能,更好地与Testcontainers和Docker Compose集成。

详细点击标题