GitHub Actions:如何缓存测试容器的 Docker 镜像?

Oli*_*ver 11 caching testcontainers github-actions

我使用 Testcontainers 在 GitHub Actions 中执行一些测试。

Testcontainers 提取我的测试中使用的图像。不幸的是,每次构建时都会再次提取图像。

如何在 GitHub Actions 中缓存图像?

rie*_*pil 12

GitHub Actions 尚未提供官方支持来支持缓存拉取的 Docker 镜像(请参阅本期本期)。

您可以做的就是拉取 Docker 映像,将它们另存为.tar存档并将它们存储在文件夹中,以便 GitHub Actions 缓存操作拾取它。

示例工作流程如下所示:

 build-java-project:
    runs-on: ubuntu-latest
    steps:
        - uses: actions/checkout@v2

        - run: mkdir -p ~/image-cache

        - id: image-cache
          uses: actions/cache@v1
          with:
              path: ~/image-cache
              key: image-cache-${{ runner.os }}

        - if: steps.image-cache.outputs.cache-hit != 'true'
          run: |
              docker pull postgres:13
              docker save -o ~/image-cache/postgres.tar alpine

        - if: steps.image-cache.outputs.cache-hit == 'true'
          run: docker load -i ~/image-cache/postgres.tar

        - name: 'Run tests'
          run: ./mvnw verify
Run Code Online (Sandbox Code Playgroud)

虽然这有点吵,但每次您依赖新的 Docker 镜像进行测试时,您都需要调整管道。另请注意如何进行缓存失效,因为我猜如果您打算使用标签:latest,上面的解决方案将无法识别图像的更改。

当前的 GitHub Actions缓存大小为 10 GB,对于依赖 5-10 个 Docker 镜像进行测试的中型项目来说应该足够了。

还有Docker GitHub Cache API,但我不确定它与 Testcontainers 的集成程度如何。