This configuration runs the workflow on pushes to the main branch and on pull
requests. By including both triggers, you can ensure that the image builds
correctly for a pull request before it's merged.
## Extract metadata for tags and annotations
For the first step in your workflow, use the `docker/metadata-action` to
generate metadata for your image. This action extracts information about your
Git repository, such as branch names and commit SHAs, and generates image
metadata such as tags and annotations.
Add the following YAML to your workflow file:
```yaml
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Extract Docker image metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ vars.DOCKER_USERNAME }}/my-image
```
These steps prepare metadata to tag and annotate your images during the build
and push process.
- The **Checkout** step clones the Git repository.
- The **Extract Docker image metadata** step extracts Git metadata and
generates image tags and annotations for the Docker build.
## Authenticate to your registry
Before you build the image, authenticate to your registry to ensure that you
can push your built image to the registry.
To authenticate with Docker Hub, add the following step to your workflow:
```yaml
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ vars.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
```
This step uses the Docker credentials [configured in the repository settings](#configure-your-github-repository).
## Build and push the image
Finally, build the final production image and push it to your registry. The
following configuration builds the image and pushes it directly to a registry.
```yaml
- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
annotations: ${{ steps.meta.outputs.annotations }}
```
In this configuration:
- `push: ${{ github.event_name != 'pull_request' }}` ensures that images are
only pushed when the event is not a pull request. This way, the workflow
builds and tests images for pull requests but only pushes images for commits
to the main branch.
- `tags` and `annotations` use the outputs from the metadata action to apply
consistent tags and [annotations](/manuals/build/metadata/annotations.md) to
the image automatically.
## Attestations
SBOM (Software Bill of Materials) and provenance attestations improve security
and traceability, ensuring your images meet modern software supply chain
requirements.
With a small amount of additional configuration, you can configure
`docker/build-push-action` to generate Software Bill of Materials (SBOM) and