Docker BuildKit Cache Not Working with GitHub Actions

Issue

When using Docker BuildKit in a GitHub Actions workflow, the build cache does not seem to persist between jobs or workflow runs, resulting in slow builds every time. The --build-arg BUILDKIT_INLINE_CACHE=1 and cache-from options are set, but caching is not effective. How can I enable persistent Docker BuildKit cache in GitHub Actions?

Solution

By default, GitHub Actions runners are ephemeral and do not persist Docker layer cache between jobs or workflow runs. To enable persistent Docker BuildKit cache, you need to use the actions/cache action to store and restore the /tmp/.buildx-cache directory. Here is an example:

- name: Set up Docker Buildx
  uses: docker/setup-buildx-action@v3

- name: Cache Docker layers
  uses: actions/cache@v4
  with:
    path: /tmp/.buildx-cache
    key: $-buildx-$
    restore-keys: |
      $-buildx-

- name: Build and push
  uses: docker/build-push-action@v5
  with:
    context: .
    push: false
    cache-from: type=local,src=/tmp/.buildx-cache
    cache-to: type=local,dest=/tmp/.buildx-cache

This setup will significantly speed up your Docker builds in GitHub Actions.