How to Keep Credentials Out of Images With Docker Build Secrets

A Docker build may need a token to fetch a private dependency. Putting the token in a Dockerfile ARG or ENV can expose it in the image or build metadata. A BuildKit secret mount gives one RUN instruction temporary access to the credential. Docker’s build secrets documentation

Mount a secret for a private package install

In CI, store the contents of your private registry’s npm configuration as a secret named NPMRC and expose it to the build job. Pass that secret to BuildKit under the ID npmrc.

docker build --secret id=npmrc,env=NPMRC .

In a Node.js build stage, after copying the package manifest and lockfile, point npm at the mounted file. The required=true option makes the step fail if the build job omits the secret.

RUN --mount=type=secret,id=npmrc,required=true NPM_CONFIG_USERCONFIG=/run/secrets/npmrc npm ci

Keep the credential out of files copied into the image and avoid printing it in build output. Use BuildKit’s SSH mount if the build needs your SSH agent to fetch a private Git dependency. If you rotate a secret and need the protected step to run again, invalidate that stage’s cache. Changing the secret alone does not rerun the step. Docker’s build cache guidance

Latest articles

Related articles