How to Build a Docker Image With Build Args From Secrets in GitHub Actions
Build args bake into image history; BuildKit secret mounts keep credentials out of the final layers.
Use docker/build-push-action with secrets: (BuildKit secret mounts) so a token is available during build but never persisted in the image.
Steps
- Reference the secret with
secrets: |in the build action. - In the Dockerfile, mount it with
RUN --mount=type=secret. - Read it from
/run/secrets/<id>during the build only. - Never pass tokens via
build-args, which persist in image metadata.
Workflow
.github/workflows/docker.yml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/build-push-action@v6
with:
context: .
push: false
secrets: |
npm_token=${{ secrets.NPM_TOKEN }}Gotchas
- Secret mounts require BuildKit (
setup-buildx-action); legacy builds cannot use them. - In the Dockerfile use
RUN --mount=type=secret,id=npm_token cat /run/secrets/npm_token. - Latchkey runs Docker builds on cheaper runners that keep BuildKit cache warm and retry transient pulls.
Related guides
How to Push a Multi-Arch Image to ECR in GitHub ActionsBuild and push a multi-arch (amd64 + arm64) Docker image to Amazon ECR in GitHub Actions using OIDC to authen…
How to Sign Commits in an Automated PR in GitHub ActionsCreate verified, signed commits from a GitHub Actions bot by committing through the GitHub API or a GitHub Ap…