How to Tag a Docker Image by Git SHA and Semver in CI
docker/metadata-action derives a consistent set of tags and OCI labels from the git context for each build.
Run docker/metadata-action with tags: rules (sha, semver, branch), then pass its tags and labels outputs to build-push-action. You get reproducible, traceable tags without hand-writing them.
Steps
- Add
docker/metadata-actionwith the image name and tag rules. - Use
type=sha,type=semver, andtype=refpatterns for the tags you want. - Wire
steps.meta.outputs.tagsandoutputs.labelsinto the build step.
Workflow
.github/workflows/docker.yml
- id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=sha
type=ref,event=branch
type=semver,pattern={{version}}
- uses: docker/build-push-action@v6
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}Gotchas
type=semvertags emit only on tag pushes; on branch pushes those entries are skipped.- By default
type=shauses a 7-char short SHA; addformat=longfor the full hash.
Related guides
How to Push a Docker Image to Docker Hub in CILog in to Docker Hub in CI with a scoped access token and push a built image, avoiding anonymous pull rate li…
How to Build Only Changed Services in a Monorepo in CIBuild Docker images only for the services that changed in a monorepo by detecting touched paths and feeding t…