Build and Push Docker Images with GitHub Actions

A
Author
13 Jun, 2026 1 min read 687 views

A common pipeline: every push to main builds an image, tags it with the commit and pushes it to a registry, ready to deploy.

The workflow

name: Docker image

on:
  push:
    branches: [main]
    tags: ['v*']

permissions:
  contents: read
  packages: write      # push to ghcr.io

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

      - uses: docker/setup-qemu-action@v3      # only needed for multi-platform builds
      - 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 }}
          tags: |
            type=sha
            type=ref,event=branch
            type=semver,pattern={{version}}

      - uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

What each piece does

  • GITHUB_TOKEN with packages: write can push to the repository's GitHub Container Registry; no extra secret needed.
  • metadata-action generates tags: the commit SHA, the branch name and semantic versions for v1.2.3 git tags.
  • cache-from/cache-to: gha reuses unchanged layers between runs.
  • platforms builds for both Intel/AMD and ARM servers (such as AWS Graviton).

Tag strategy

Deploy using the immutable SHA tag, not latest or a branch name, so you always know exactly which code is running and can roll back precisely.

On pull requests

Build without pushing (push: false) to catch Dockerfile errors before merge, and consider running an image scanner such as Trivy on the result.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.