Build a Docker image in GitHub Actions
Build a Docker image in GitHub Actions with docker/build-push-action, tag it from the Git ref and cache layers in the Actions cache.
Three official actions cover login, tags and build. Layer caching in the Actions cache makes repeat builds quick.
name: Image
on:
push:
branches: [main]
permissions:
contents: read
packages: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
- uses: docker/build-push-action@v6
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=maxmetadata-action makes tags such as the branch name and the short commit SHA from the event. type=gha stores layers in the Actions cache, so unchanged layers are not rebuilt. mode=max caches intermediate stages too, which matters for a multi-stage Dockerfile. See Docker's GitHub Actions cache guide.
The built-in GITHUB_TOKEN can push to GitHub's registry with packages: write. For another registry, use its own credentials from secrets.