Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 44 ยท GitHub Actions in Practice

Building and Pushing Docker Images

Build, tag and push container images from GitHub Actions with Buildx, docker/build-push-action, GHCR login, layer caching and multi-platform builds.

A pipeline that only tests your code leaves the last mile to humans. For most modern services the thing you actually deploy is a container image, so a good workflow also builds that image, gives it meaningful tags and pushes it to a registry where servers can pull it. Doing this in CI means every image comes from a known commit, built the same way every time, not from someone's laptop.

This lesson assumes you know what an image, a layer and a registry are. If not, start with the Docker tutorial, especially The Build Cache, Multi-Platform Images and Image Tagging Strategy. Here we focus on the workflow: the set of actions that log in, build and push, how tags are generated, how to reuse layers between runs, and how to build for more than one CPU architecture. As in the rest of this track, the workflow YAML is read-only (it needs GitHub and a registry), and the runnable example is a stand-in that shows how tags are derived.

The four-step recipe

Almost every image workflow is the same four steps:

flowchart LR
    A["checkout"] --> B["setup-buildx"]
    B --> C["login to registry"]
    C --> D["metadata: compute tags"]
    D --> E["build-push-action"]

Check out the code, prepare the builder, log in, compute tags and labels, then build and push in one step.

Here is a complete example that publishes to the GitHub Container Registry (GHCR, ghcr.io):

YAML
name: Publish image

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

permissions:
  contents: read
  packages: write

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

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

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

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

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

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

Let us walk through the parts that are not obvious.

Permissions and the registry login

The workflow asks for packages: write so that the automatic GITHUB_TOKEN is allowed to push to GHCR. Because the token is created per run and expires when the run ends, you do not need to store a long-lived registry password. Compare this with Docker Hub, where you would create an access token and store it as a repository secret (see Secrets, Variables and Environment Variables), then pass username and password from secrets.

The login step is skipped for pull requests. Two reasons: pull requests from forks get a read-only token that cannot push, and you generally do not want to publish images for unreviewed code. The build still runs on pull requests (with push: false), so a broken Dockerfile is caught before merge.

Image names on GHCR must be lowercase. github.repository can contain uppercase letters if your account or repository name does, in which case the push fails. The metadata action lowercases image names for you, which is another reason to feed the name through it.

Buildx and build-push-action

docker/setup-buildx-action sets up Docker Buildx, the front end for BuildKit (see BuildKit). The docker/build-push-action then runs docker buildx build for you, with inputs for the context, Dockerfile path, build arguments, tags, labels, cache and platforms. Using the action rather than a raw run: docker build gives you cache export, multi-platform support, build summaries and a consistent push step.

The push input decides whether the finished image goes to the registry. Setting it to an expression like ${{ github.event_name != 'pull_request' }} is a common way to build everywhere but publish only from trusted events.

Tags from metadata

Typing tag names by hand in YAML is error-prone, so the usual approach is docker/metadata-action. You describe rules, and it produces the tag list and the OCI labels (source repository, revision, creation time) from the event that triggered the run. Some of the common rules:

Rule Triggered by Example result
type=ref,event=branch a push to a branch main, feature-login (slashes become dashes)
type=ref,event=pr a pull request pr-42
type=semver,pattern={{version}} a tag like v1.2.3 1.2.3
type=semver,pattern={{major}}.{{minor}} a tag like v1.2.3 1.2
type=sha any push sha- plus the first seven characters of the commit

With semantic-version tags, one release produces several tags (1.2.3, 1.2, and optionally 1). People can then choose how tightly to pin: exactly 1.2.3, or "any 1.2.x patch". Unless you configure it otherwise, the action also adds latest for a stable version tag. Pre-release versions such as v2.0.0-rc.1 get only their full version, and a 0.x release does not get a bare major tag, because a major of zero promises no stability.

The sha-... tag is the one to deploy: it points to exactly one commit. Movable tags such as main or 1.2 are convenient for humans, but deploying from a tag that can change under you makes rollbacks and audits harder. For production, pin by the SHA tag or, better, by the image digest (the sha256:... content hash).

Stand-in: a tag generator

The real action does much more (schedules, custom prefixes, flavors). The stand-in below implements the core rules from the table so you can see how one event becomes a tag list. It is plain JavaScript and the output is deterministic.

JS From a Git event to image tags

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the last two events: the release candidate never receives latest, and the 0.3.1 release gets no 0 tag. Those rules protect users who pull latest or a major tag from accidentally receiving an unstable build.

Layer caching

Docker reuses unchanged layers on your laptop because the layers are still on disk. A fresh CI runner has nothing, so every run starts cold and reinstalls all dependencies, unless you export the cache somewhere persistent. The action supports several cache backends through cache-from and cache-to:

YAML
# 1. The GitHub Actions cache (simple, size-limited, per repository)
cache-from: type=gha
cache-to: type=gha,mode=max

# 2. A cache image in your registry (works across machines and CI systems)
cache-from: type=registry,ref=ghcr.io/acme/shop-api:buildcache
cache-to: type=registry,ref=ghcr.io/acme/shop-api:buildcache,mode=max

mode=max exports the layers of every stage of a multi-stage build, not just the final image, which usually gives far better hit rates because the expensive dependency-install stages are cached. The gha backend is the least work, but the GitHub cache has a size limit per repository and evicts old entries, so a large image with many branches can thrash it. A registry cache costs storage but scales further.

The ordering rules you learned in The Build Cache still matter most: copy lock files and install dependencies before copying source code, or even a perfect cache backend will miss on every commit.

Multi-platform images

Laptops with Arm processors and many cloud servers run linux/arm64, while most CI runners are linux/amd64. A multi-platform image is one tag that points to a separate image per architecture, and the client picks the matching one automatically. To build one, add QEMU emulation and the platforms input:

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

      - uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}

Emulating Arm on an x86 runner works but is slow, often several times slower for compile-heavy builds. If that hurts, there are two common remedies: use native Arm runners (GitHub offers hosted Arm runners, and you can add self-hosted ones; see Self-Hosted Runners and Runner Costs), or cross-compile inside the Dockerfile with a language that makes this easy, such as Go. Also remember that a multi-platform result usually cannot be loaded into the local Docker image store on the runner; it must be pushed (or exported) rather than just built.

Security notes

  • Give the job the least permissions: contents: read plus packages: write only on the job that pushes.
  • Do not push images built from fork pull requests; the push expression above prevents it.
  • Never put secrets in build-args. Build arguments are recorded in image history. BuildKit has dedicated secret mounts for build-time credentials.
  • Scan the image and consider signing it. These steps come up again in Securing Your Pipeline and the project on building, scanning and deploying a container.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the example skip the registry login on pull requests?

    Tokens for fork pull requests are read-only and cannot push. Even for same-repo PRs, you normally only publish images after the code has been reviewed and merged.
  2. 2. What does type=sha in docker/metadata-action give you that type=ref,event=branch does not?

    Branch tags such as main move with every push. A SHA tag identifies one commit, which makes deployments, rollbacks and audits reliable.
  3. 3. What does cache-to: type=gha,mode=max change compared with the default mode?

    mode=max includes intermediate stages of multi-stage builds, so dependency-install stages are reused on later runs.
  4. 4. A tag v2.0.0-rc.1 is pushed. What should a sensible tagging setup do?

    Pre-releases are published under their full version only. Moving latest or the major tag would hand unstable builds to people who asked for the stable line.
  5. 5. Which permission lets the automatic GITHUB_TOKEN push an image to GHCR?

    packages: write allows publishing packages and container images. Granting only what the job needs follows least privilege.

Summary

  • An image workflow has four steps: set up Buildx, log in, compute tags and labels with docker/metadata-action, then build and push with docker/build-push-action.
  • GHCR needs no stored password: the per-run GITHUB_TOKEN with packages: write is enough.
  • Build on pull requests but push only from trusted events.
  • Use semver tags for humans and the sha- tag (or the digest) for deployments.
  • Export the layer cache with cache-from / cache-to; mode=max caches multi-stage builds well.
  • Multi-platform builds need QEMU or native runners and must be pushed, not just loaded locally.

Next, you will learn how to stop copying these workflows between repositories: Reusable Workflows and Composite Actions.