如何在 github-action 中缓存 docker-compose 构建

Ash*_*hik 8 github docker-compose docker-build github-actions building-github-actions

有没有办法缓存 docker-compose 以便它不会一次又一次地构建?这是我的操作工作流文件:

name: Github Action
on:
  push:
    branches:
      - staging
jobs:
  test:
    runs-on: ubuntu-18.04

    steps:
      - uses: actions/checkout@v1

      - name: Bootstrap app on Ubuntu
        uses: actions/setup-node@v1
        with:
          node-version: '12'


      - name: Install global packages
        run: npm install -g yarn prisma


      - name: Install project deps
        if: steps.cache-yarn.outputs.cache-hit != 'true'
        run: yarn


      - name: Build docker-compose
        run: docker-compose -f docker-compose.test.prisma.yml up --build -d

Run Code Online (Sandbox Code Playgroud)

我想缓存 docker build 步骤。我试过使用if: steps.cache-docker.outputs.cache-hit != 'true' then only build 但没有用。

Byt*_*yte 14

这个问题很老了,但我发现自己试图解决完全相同的问题。在阅读了许多不同的答案并花费了大量时间后,我最终找到了一个不错的解决方案。

我的工作流程文件现在如下所示:

jobs:
  build:
    name: Integration tests
    runs-on: ubuntu-22.04
    # I need "packages: write" to access GHCR.
    # More about permissions here: https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs
    permissions: write-all
    steps:
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Login to Docker Registry
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - uses: actions/checkout@v2

      - name: Build docker-compose
        # Before the cache, it was "run: docker compose build".
        run: docker buildx bake --file docker-compose.yml --file docker-compose-cache.json

...
Run Code Online (Sandbox Code Playgroud)

docker-compose-cache.json文件中,我有以下内容:

{
  "target": {
    "service-name": {
      "cache-from": [
        "type=registry,ref=ghcr.io/MY_GITHUB_ORG_NAME/service-name:cache"
      ],
      "cache-to": [
        "type=registry,ref=ghcr.io/MY_GITHUB_ORG_NAME/service-name:cache"
      ],
      "output": [
        "type=docker"
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

对于 in 中的每项服务docker-compose.yml,我添加一个targetin docker-compose-cache.jsondocker buildx bake从 获取构建指令docker-compose.yml并从 缓存指令docker-compose-cache.json

这样我还是可以docker-compose up --build像平常一样在本地使用。

您可能会注意到,我使用 GitHub 容器注册表而不是 GitHub 操作缓存,因为 GHCR 对缓存大小没有限制。


小智 12

对于那些通过谷歌到达这里的人来说,这现在是“支持的”。或者至少它正在工作:https://github.community/t/use-docker-layer-caching-with-docker-compose-build-not-just-docker/156049。这个想法是使用 docker (及其缓存)构建图像,然后使用 docker compose 来运行(启动)它们。


Dan*_*nyB 10

您所指的称为“docker 层缓存”,GitHub Actions 尚不支持它。

这在几个地方被广泛讨论,例如:

正如评论中所提到的,有一些 3rd 方操作提供了这个功能(比如这个),但是对于这样一个核心和基本功能,我会对 GitHub 本身没有正式支持的任何东西持谨慎态度。