Skip to content
jshacks.dev
Tooling

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.

1 min read
Summarize in AI

Three official actions cover login, tags and build. Layer caching in the Actions cache makes repeat builds quick.

.github/workflows/image.ymlYAML
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=max

metadata-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.

Share

More snippets

Tooling

Create a Vite project from a template

Create a Vite project from a template with npm create vite, choose the vanilla-ts or react-ts template and see which files it generates.

1 min read
Tooling

Configure VS Code settings for a team

Share VS Code settings and recommended extensions with a team by committing a .vscode folder with settings.json and extensions.json.

1 min read
Tooling

Share an ESLint config across packages

Share one ESLint 9 flat config across workspace packages by exporting an array from a package and spreading it into each package's eslint.config.js.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.