CI/CD with Docker: Building, Tagging, and Pushing Images Automatically

Docker CI/CD in GitHub Actions: build, tag by commit, cache, scan and push images, then promote the same digest to production.

Executive Summary: A good container pipeline builds each commit exactly once, tags the image with the commit SHA so it can always be traced back to source, caches builds so they take seconds rather than minutes, scans and signs the image, and promotes that same image digest through environments instead of rebuilding it. Human-friendly tags such as 1.8.0 are added on release, and latest never drives a production deployment. Below is a complete GitHub Actions workflow that does all of it.
Isometric cargo ship carrying coloured containers along a build, tag and push route towards a registry cloud

A team builds images on a developer’s laptop, tags them latest and pushes them. Production pulls latest on every restart. One Friday, a half-finished build gets pushed by accident, a server reboots over the weekend, and production starts running code that never went through review. Nobody can tell which commit is running, because every image is called latest.

CI/CD with Docker means producing images automatically from version control, with a pipeline that builds, tests, scans, signs and publishes them, and deployments that reference images by immutable identifiers. I described an AWS-native pipeline for application deployments earlier this year in setting up a CI/CD pipeline in AWS; the focus here is the container image side, which works the same on any CI system.

The pipeline, stage by stage

  1. Build the image once, with BuildKit and a persistent cache.
  2. Test inside the image or against it, so you test exactly what ships.
  3. Scan for known vulnerabilities and fail on fixable critical findings.
  4. Push to a registry with immutable tags.
  5. Sign the pushed digest and attach SBOM and provenance.
  6. Deploy by digest, and promote the same digest from staging to production.

A tagging strategy that stays honest

Tag When Mutable? Use
sha-3f9c2e1 Every build Never Traceability; deployments reference this or the digest
main, pr-482 Branch and pull request builds Yes, moves with the branch Preview environments and manual testing
1.8.0, 1.8, 1 On a release tag in Git 1.8.0 never; 1.8 and 1 move to the newest patch Consumers who want a version line
latest Optional, on release Yes Convenience for humans, never for production manifests

The principle: every image has at least one tag that will never point to anything else, and production always deploys an immutable reference. Many registries, including ECR, can enforce tag immutability so a 1.8.0 can never be overwritten.

A complete GitHub Actions workflow

name: image

on:
  push:
    branches: [main]
    tags: ["v*.*.*"]
  pull_request:

permissions:
  contents: read
  packages: write
  id-token: write     # for keyless signing with Cosign

env:
  IMAGE: ghcr.io/${{ github.repository }}

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: docker/setup-qemu-action@v3
      - uses: docker/setup-buildx-action@v3

      - uses: docker/login-action@v3
        if: github.event_name != 'pull_request'
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.IMAGE }}
          tags: |
            type=sha,prefix=sha-
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}

      - name: Build and test
        uses: docker/build-push-action@v5
        with:
          context: .
          target: test
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - id: build
        name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          target: prod
          platforms: linux/amd64,linux/arm64
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          sbom: true
          provenance: mode=max
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Scan
        if: github.event_name != 'pull_request'
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: ${{ env.IMAGE }}@${{ steps.build.outputs.digest }}
          severity: CRITICAL,HIGH
          ignore-unfixed: true
          exit-code: "1"

      - uses: sigstore/cosign-installer@v3
        if: github.event_name != 'pull_request'
      - name: Sign
        if: github.event_name != 'pull_request'
        run: cosign sign --yes ${{ env.IMAGE }}@${{ steps.build.outputs.digest }}

What each piece does:

  • metadata-action generates the tags from the table above based on the Git event, so the logic is declarative rather than shell scripting.
  • The test build uses the test stage of a multi-stage Dockerfile, so tests run in the same environment as production. The shared cache means the second build reuses the dependency layers.
  • cache-from and cache-to with type=gha store BuildKit’s cache in the GitHub Actions cache, as described in the build cache article.
  • QEMU and platforms produce a multi-architecture image for both Intel servers and ARM machines such as AWS Graviton and Apple Silicon. Emulated ARM builds are slower; native ARM runners or splitting the build per platform helps for heavy compiles.
  • The scan and the signature target the pushed digest, not a tag, so they refer to exactly the bytes that will run. Supply chain details are in image scanning and supply chain security.
  • Pull requests build and test but do not push, which keeps credentials away from code from forks.

Registry authentication without long-lived keys

The workflow uses the built-in GITHUB_TOKEN for GitHub Container Registry. For cloud registries, use OpenID Connect federation instead of storing access keys as secrets: aws-actions/configure-aws-credentials assumes an IAM role for Amazon ECR, and Google and Azure have equivalent actions. The CI job receives short-lived credentials scoped to one repository, and there is no key to rotate or leak.

Promote, do not rebuild

Rebuilding the same commit for production produces a different image: base images may have changed, dependency resolution may differ, and the timestamp certainly will. The image you tested in staging is then not the image in production. Instead, deploy staging with the digest from the build, and promote that exact digest to production after approval. If you want a release tag, add it to the existing image without rebuilding:

docker buildx imagetools create \
  --tag ghcr.io/acme/billing-api:1.8.0 \
  ghcr.io/acme/billing-api@sha256:4f2c9d...

For deployment, the two common patterns are pushing the new digest to servers (for example SSH plus docker compose pull && docker compose up -d with the tag pinned in an environment file) or GitOps, where the pipeline commits the new digest to a deployment repository and an agent on the platform applies it. GitOps leaves an audit trail of every production change in Git.

Other CI systems

  • GitLab CI can build with a docker:dind service, which needs privileged runners, or with daemonless builders such as Kaniko or BuildKit’s rootless mode. Its built-in container registry and CI_COMMIT_SHORT_SHA variable map directly to the tagging strategy above.
  • Jenkins, CircleCI and Buildkite all run docker buildx the same way; the cache can be exported to a registry with type=registry when the CI system has no native cache backend.

Housekeeping

A pipeline that pushes every commit creates thousands of tags. Set registry lifecycle rules: keep release tags forever, keep the last few hundred SHA tags, and expire pull request and branch images after a couple of weeks. Make sure the retention window comfortably covers any image you might need to roll back to.

Frequently Asked Questions

How should I tag Docker images in CI?

Tag every build with an immutable identifier such as the Git commit SHA, add branch or pull request tags for previews, and add semantic version tags on releases. Deploy production by an immutable tag or digest, never by latest.

Why not use the latest tag in production?

latest is a movable pointer with no link to a specific commit. Deployments become unrepeatable, rollbacks are guesswork, and any accidental push changes what production runs on its next restart.

How do I speed up Docker builds in GitHub Actions?

Use docker/build-push-action with Buildx and set cache-from and cache-to to type=gha with mode=max, so BuildKit layer caches, including intermediate stages, persist between workflow runs. Also order your Dockerfile so dependencies are installed before source code is copied.

Should I rebuild the image for production after testing in staging?

No. Promote the exact image digest that passed staging. Rebuilding can pull different base images or dependencies, so production would run an image that was never tested.

Build once, trace always

The goal of a container pipeline is boring certainty: every running container maps to one commit, one build, one scan report and one signature, and the bytes that were tested are the bytes that run. Immutable tags, cached Buildx builds, digest-based scanning and signing, and promotion instead of rebuilding get you there with a single workflow file. The official documentation is worth keeping open: the Docker GitHub Actions guide and the GitHub Actions documentation. Related reading on this site: Docker secrets.

Originally posted on 31 October 2023 and post last modified on 31 October 2023

CI/CD DevOps Docker GitHub Actions

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *