docker/build-push-action

repository·master·Indexed 20 days ago

https://github.com/docker/build-push-action

A GitHub Action to build and push Docker images using Buildx and Moby BuildKit. It supports multi-platform builds, secrets, remote caching, and detailed build summaries. The action provides flexible build context options (Git and Path), supports provenance and SBOM attestations, and allows configuration via a comprehensive set of inputs and environment variables.

Tokens
3.5K
Snippets
4
Records
16
Agent score
89%

What's inside docker-build-push-action

  1. Authenticate against private Git repositories

    master

    While building from the current repository uses the automatic GitHub Token, you must provide a secret named GIT_AUTH_TOKEN if you need to authenticate against a different private repository during the build process.

          -
            name: Build and push
            uses: docker/build-push-action@v7
            with:
              push: true
              tags: user/app:latest
              secrets: |
                GIT_AUTH_TOKEN=${{ secrets.MYTOKEN }}
  2. View build execution summaries

    master

    The action automatically generates a GitHub job summary providing an overview of build execution, including inputs and errors. It also produces a build record (with .dockerbuild extension) containing build stats and logs that can be imported into Docker Desktop.

    Note for actions/download-artifact users: If you use actions/download-artifact@v4 without specifying a name or pattern, the workflow may fail because it tries to download the build record artifacts. To avoid this, use a negative pattern to ignore them:

    - uses: actions/download-artifact@v4
      with:
        pattern: "!*.dockerbuild"
  3. Build and push Docker images using Git context

    master

    By default, docker/build-push-action uses the Git context, meaning you do not need to use actions/checkout to check out your repository; BuildKit handles the checkout directly from the Git reference.

    Important: Because the context is based on the Git reference, any file mutations (changes) made in previous steps—including modifications to the .dockerignore file—will be ignored.

    To use a specific subdirectory within the default Git context, use the Handlebars template expression {{defaultContext}} with a colon separator.

          -
            name: Build and push
            uses: docker/build-push-action@v7
            with:
              context: "{{defaultContext}}:mysubdir"
              push: true
              tags: user/app:latest
  4. Build and push Docker images using Path context

    master

    If you need to perform file mutations (like generating files or modifying .dockerignore) before the build step, you must use the Path context. This requires using the actions/checkout action to explicitly check out the repository into the runner's filesystem, and then setting the context input to . (or your specific path).

    name: ci
    
    on: push
    
    jobs:
      docker:
        runs-on: ubuntu-latest
        steps:
          -
            name: Checkout
            uses: actions/checkout@v6
          -
            name: Login to Docker Hub
            uses: docker/login-action@v4
            with:
              username: ${{ vars.DOCKERHUB_USERNAME }}
              password: ${{ secrets.DOCKERHUB_TOKEN }}
          -
            name: Set up QEMU
            uses: docker/setup-qemu-action@v4
          -
            name: Set up Docker Buildx
            uses: docker/setup-buildx-action@v4
          -
            name: Build and push
            uses: docker/build-push-action@v7
            with:
              context: .
              push: true
              tags: user/app:latest
  5. Configure Attestations (Provenance and SBOM)

    master

    The action supports adding attestations to your builds.

    • Provenance: Use the provenance input or include type=provenance in the attests list.
    • SBOM: Use the sbom input or include type=sbom in the attests list.
    • Default Behavior: If attests is not provided and BuildKit version is compatible (>= 0.11.0), the action sets default provenance based on repository visibility:
      • Private Repositories: mode=min,inline-only=true
      • Public Repositories: mode=max

    Note: Attestations require buildx >= 0.10.0.

  6. Fix `repository name must be lowercase` error

    master

    The error invalid reference format: repository name must be lowercase occurs when using a repository slug that contains uppercase characters (for example, using github.repository directly in a tag).

    To resolve this, you must ensure the image tags are sanitized to lowercase. You can do this using the docker/metadata-action or by using a custom script to lowercase the slug.

    ### Option 1: Use docker/metadata-action (Recommended)
    
    ```yaml
    - name: Docker meta
      id: meta
      uses: docker/metadata-action@v6
      with:
        images: ghcr.io/${{ github.repository }}
        tags: latest
    
    - name: Build and push
      uses: docker/build-push-action@v7
      with:
        push: true
        tags: ${{ steps.meta.outputs.tags }}

    Option 2: Sanitize the slug manually with github-script

    - name: Sanitize repo slug
      uses: actions/github-script@v8
      id: repo_slug
      with:
        result-encoding: string
        script: return 'ghcr.io/${{ github.repository }}'.toLowerCase()
    
    - name: Build and push
      uses: docker/build-push-action@v7
      with:
        push: true
        tags: ${{ steps.repo_slug.outputs.result }}:latest
  7. Debug registry push failures

    master

    If you encounter errors during the push process (such as invalid content digest, no response, 400 Bad Request, or 401 Unauthorized), these issues are typically related to Buildx, BuildKit, containerd, or the destination registry rather than the build-push-action itself.

    To diagnose these issues, you must enable debugging in the setup-buildx action step and provide the BuildKit container logs when reporting the issue.

  8. Configure build checks annotations via environment variables

    master

    You can control whether build warnings are converted into GitHub annotations using the DOCKER_BUILD_CHECKS_ANNOTATIONS environment variable. By default, this is enabled.

    Set DOCKER_BUILD_CHECKS_ANNOTATIONS to false to disable this feature.

  9. Configure build summary via environment variables

    master

    The build summary feature (which provides a detailed report in the GitHub Action summary) can be controlled via environment variables:

    • DOCKER_BUILD_SUMMARY: Set to false to disable the build summary.
    • DOCKER_BUILD_RECORD_UPLOAD: Set to true to enable uploading the build record as a GitHub artifact.
    • DOCKER_BUILD_RECORD_RETENTION_DAYS: Specifies the number of days to retain the uploaded build record artifact.
  10. Configure docker/build-push-action inputs

    master

    The docker/build-push-action accepts several inputs via the step.with key in a GitHub Actions workflow.

    Data Formats:

    • List type: A newline-delimited string.
      cache-from: |
        user/app:cache
        type=local,src=path/to/dir
    • CSV type: A comma-delimited string.
      tags: name/app:latest,name/app:1.0.0

    Common Inputs:

    NameTypeDescription
    add-hostsList/CSVCustom hosts mapping (e.g., docker:10.180.0.1)
    allowList/CSVExtra privileged entitlements (e.g., network.host,security.insecure)
    annotationsListAnnotations to set on the image
    attestsListAttestation parameters (e.g., type=sbom,generator=image)
    builderStringBuilder instance (from setup-buildx-action)
    build-argsListBuild-time variables
    build-contextsListAdditional build contexts (e.g., name=path)
    cache-fromListExternal cache sources (e.g., type=local,src=path/to/dir)
    cache-toListCache export destinations (e.g., type=local,dest=path/to/dir)
    callStringMethod for evaluating build (e.g., check)
    cgroup-parentStringParent cgroup for the build container
    contextStringBuild context path or URL (default: Git context)
    fileStringPath to Dockerfile (default: {context}/Dockerfile)
    labelsListImage metadata
    loadBoolShorthand for --output=type=docker (default: false)
    networkStringNetworking mode for RUN instructions
    no-cacheBoolDisable cache usage (default: false)
    no-cache-filtersList/CSVStages to not cache
    outputsListOutput destinations (format: type=local,dest=path)
    platformsList/CSVTarget platforms (e.g., linux/amd64,linux/arm64)
    provenanceBool/StringGenerate provenance attestation (shorthand for --attest=type=provenance)
    pullBoolAlways attempt to pull referenced images (default: false)
    pushBoolShorthand for --output=type=registry (default: false)
    sbomBool/StringGenerate SBOM attestation (shorthand for --attest=type=sbom)
    secretsListSecrets to expose (e.g., key=string, GIT_AUTH_TOKEN=mytoken)
    secret-envsList/CSVSecret env vars (e.g., key=envname, MY_SECRET=MY_ENV_VAR)
    secret-filesListSecret files (e.g., key=filename, MY_SECRET=./secret.txt)
    shm-sizeStringSize of /dev/shm (e.g., 2g)
    sshListSSH agent sockets or keys
    tagsList/CSVImage tags
    targetStringTarget stage to build
    ulimitListUlimit options (e.g., nofile=1024:1024)
    github-tokenStringGitHub Token for Git context (default: ${{ github.token }})
  11. Configure docker/build-push-action environment variables

    master

    You can control the behavior of the action using the following environment variables:

    NameTypeDefaultDescription
    DOCKER_BUILD_CHECKS_ANNOTATIONSBooltrueIf false, GitHub annotations are not generated for build checks
    DOCKER_BUILD_SUMMARYBooltrueIf false, build summary generation is disabled
    DOCKER_BUILD_RECORD_UPLOADBooltrueIf false, build record upload as GitHub artifact is disabled
    DOCKER_BUILD_RECORD_RETENTION_DAYSNumberDuration after which build record artifact will expire in days. Defaults to repository/org retention settings if unset or 0