GitHub Actions Docker Build and Push with Layer Caching
Build and push Docker images from GitHub Actions with BuildKit layer caching. Covers the gha and registry cache backends and GHCR permissions.
At a glance
- Last reviewed
- Versions referenced
actions/checkout@v7docker/setup-buildx-action@v4docker/login-action@v4docker/metadata-action@v6docker/build-push-action@v7docker/setup-qemu-action@v4- Reading time
- 3 min read
Code samples are not run in a live repository. See our editorial standards.
On this page
Set cache-from: type=gha and cache-to: type=gha,mode=max on the docker/build-push-action step, and run docker/setup-buildx-action before it. Buildx stores layers in the GitHub Actions cache, so later runs reuse them instead of rebuilding from scratch. Without a cache backend, every job starts on a fresh runner with an empty layer cache.
Build and push to GHCR and Docker Hub with the gha cache
Put this in .github/workflows/docker-publish.yml. It pushes to both GitHub Container Registry (GHCR) and Docker Hub.
name: Build and Push Docker Image
on:
push:
branches:
- main
tags:
- 'v*.*.*'
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Check out repository
uses: actions/checkout@v7
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Log in to GitHub Container Registry
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@v6
with:
images: |
ghcr.io/${{ github.repository }}
docker.io/${{ vars.DOCKERHUB_USERNAME }}/app
tags: |
type=ref,event=branch
type=semver,pattern={{version}}
- name: Build and push Docker image
uses: docker/build-push-action@v7
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
Create DOCKERHUB_USERNAME as a repository variable and DOCKERHUB_TOKEN as a secret. Use a Docker Hub access token, not your account password. GitHub-hosted runners are not subject to Docker Hub pull and push rate limits.
What each cache option does
cache-from: type=ghatells BuildKit to look in the GitHub Actions cache for layers from earlier builds.cache-to: type=gha,mode=maxexports layers from all stages, including intermediate ones. The defaultmode=minexports only layers of the final image, which misses most of the cost in multi-stage builds.docker/setup-buildx-actionis required because the default Docker builder does not support theghacache backend.
The GitHub Actions cache has a per-repository size limit, and old entries are evicted. A mode=max export of large images can push out other caches in the same repository. If you see cache misses on builds that should hit, check the repository’s Actions cache list first.
Why builds are slow without a cache
GitHub-hosted runners are ephemeral virtual machines, so the local layer cache disappears when the job ends. Every run then re-downloads base images and repeats every apt-get, apk, npm install or pip install step.
Buildx fixes this by exporting the layer cache to an external backend, such as the GitHub Actions cache or a container registry. On the next run, BuildKit checks that backend, matches layers by their content and instruction hash, and skips any step whose inputs have not changed.
Cache hits depend on Dockerfile order. Copy dependency manifests and install dependencies before copying the rest of the source. If COPY . . comes first, any source change invalidates every layer after it.
FROM node:22-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
Multi-platform builds with QEMU
Add docker/setup-qemu-action before Buildx and list the target platforms on the build step. QEMU emulates foreign CPU architectures so RUN instructions can execute for them on an x86-64 runner.
name: Build and Push Multi-Platform Image
on:
push:
tags:
- 'v*'
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Check out repository
uses: actions/checkout@v7
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Log in to GHCR
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract image metadata
id: meta
uses: docker/metadata-action@v6
with:
images: ghcr.io/${{ github.repository }}
- name: Build and push
uses: docker/build-push-action@v7
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
platforms: linux/amd64,linux/arm64
cache-from: type=registry,ref=ghcr.io/${{ github.repository }}:buildcache
cache-to: type=registry,ref=ghcr.io/${{ github.repository }}:buildcache,mode=max
This example uses the registry cache backend instead of gha. The cache is stored as an image in GHCR, so it does not count against the Actions cache limit and survives cache eviction. The registry ref must be lowercase, so if your repository name contains uppercase letters, the push of the cache fails. Use a lowercase literal in that case.
Buildx produces one image per platform and publishes a manifest list that points to them. The runner must be Linux, since QEMU emulation applies to Linux containers.
Emulated steps run much slower than native ones. If an arm64 build takes too long under QEMU, build each platform on a native runner and merge the results into one manifest. Caching helps most here, because unchanged layers are never re-executed under emulation.
GHCR permissions
Set permissions: packages: write on the workflow or job so GITHUB_TOKEN can push to GHCR. Without it, the push is rejected with a permission error. Keep contents: read so checkout still works, because setting any permissions key resets unlisted scopes to none.
If you authenticate with a personal access token instead of GITHUB_TOKEN, the token needs the write:packages scope. Prefer GITHUB_TOKEN, since it expires when the job ends.
A first push creates the package in GHCR. If the package already exists and is linked to a different repository, grant this repository write access in the package settings under Manage Actions access.
Verify the cache works
Run the workflow twice without changing the Dockerfile or source, then open the log of the build step on the second run. Unchanged steps are marked CACHED in the BuildKit output, for example #7 [3/5] RUN npm ci followed by #7 CACHED.
If every step re-executes, check these in order:
docker/setup-buildx-actionruns before the build step.cache-tois set.cache-fromalone never writes a cache.- The earlier run completed successfully and exported the cache. A failed job may not export.
- An early
Dockerfileinstruction, such as aCOPYof a file that changes every run, is not invalidating later layers.
To confirm the push, check the build step log for the exported manifest and the image’s tags under the repository’s Packages section.
Spotted an error? Report it on our Contact page and see our editorial standards for how we correct articles.