Containers and Kubernetes · Intermediate · 17 min
Use secrets in Docker builds without leaking them into the image
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Docker Engine 29.10 with BuildKit · Trivy 0.76.2
You will find a token and a private key leaking through a Docker build with Trivy 0.76, then fix the build with secret and SSH mounts, carry the fix into Compose and GitHub Actions, and prove with a rescan that the build context is clean.
On this page
Most builds need a secret at some point: a token to install a private package, an SSH key to clone a private repository, a password for an internal mirror. The quick ways to get one into a build all leave a copy behind. A --build-arg value is recorded in the image history. An ENV line is stored in the image configuration and set in every container. A key copied in with COPY sits in a layer for as long as the image exists, even if a later step deletes it. Anyone who can pull the image can read all three.
In this tutorial you build a small Node.js project with those mistakes on purpose, using a made-up GitHub token and a throwaway SSH key. You catch the leaks with Trivy before anything is built, then fix the Dockerfile with BuildKit's secret and SSH mounts, which hand the build a secret for one RUN step and keep it out of every layer. Then you make the same fix work in Docker Compose and GitHub Actions, and rescan to prove the build context is clean.
Everything happens in a throwaway folder, ~/build-secrets-demo. The app folder inside it is the build context; the secrets folder next to it is where secrets live from now on.
Step 1 · Install Trivy
Trivy is an open-source scanner from Aqua Security. Its secret scanner reads files and matches them against a few hundred rules for keys and tokens; its config scanner checks Dockerfiles for risky patterns. Install the tools this tutorial uses, then download the Trivy 0.76.2 release for your processor and check it against the published checksums before you install it:
sudo apt update
sudo apt install -y curl ca-certificates openssh-clientTRIVY_VERSION=0.76.2
case "$(dpkg --print-architecture)" in
amd64) TRIVY_ARCH=Linux-64bit ;;
arm64) TRIVY_ARCH=Linux-ARM64 ;;
*) echo "No Trivy download for this processor in this tutorial"; false ;;
esac
mkdir -p ~/build-secrets-demo/download
cd ~/build-secrets-demo/download
curl -fsSLO "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_${TRIVY_ARCH}.tar.gz"
curl -fsSLO "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_checksums.txt"
grep " trivy_${TRIVY_VERSION}_${TRIVY_ARCH}.tar.gz\$" "trivy_${TRIVY_VERSION}_checksums.txt" | sha256sum -c -
tar -xzf "trivy_${TRIVY_VERSION}_${TRIVY_ARCH}.tar.gz" trivy
sudo install -m 755 trivy /usr/local/bin/trivy
trivy --versionA binary installed this way gets no updates from apt. To upgrade, run the same block with a newer TRIVY_VERSION from the Trivy releases page. If you would rather have apt keep it current, Trivy's installation guide describes Aqua's own apt repository.
Check it worked
sha256sum -c prints the tarball name followed by OK. trivy --version starts with Version: 0.76.2.
Step 2 · Create a project that leaks its secrets
Make the project. The app is a tiny HTTP server with no dependencies, so the build does not depend on any registry you lack access to. The .npmrc file tells npm to use GitHub Packages for packages under @your-org and to read the token from the GITHUB_TOKEN environment variable, which is how a real project would pull a private package:
mkdir -p ~/build-secrets-demo/app ~/build-secrets-demo/secrets
cd ~/build-secrets-demo/app
cat > server.js <<'JS'
const http = require('node:http')
const port = process.env.PORT || 3000
http.createServer((req, res) => {
res.end('secrets demo\n')
}).listen(port, () => console.log(`listening on ${port}`))
JS
cat > package.json <<'JSON'
{
"name": "secrets-demo",
"version": "1.0.0",
"private": true,
"main": "server.js"
}
JSON
cat > package-lock.json <<'JSON'
{
"name": "secrets-demo",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "secrets-demo",
"version": "1.0.0"
}
}
}
JSON
cat > .npmrc <<'NPMRC'
@your-org:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}
NPMRCNow plant the two secrets a developer typically leaves in a project folder: a .env file with a GitHub token for local use, and a deploy key for cloning a private repository. The token here is 36 random characters after ghp_, the shape of a GitHub classic token, and works nowhere. The key is a new throwaway key with no access to anything. Both files are created private from the start:
cd ~/build-secrets-demo/app
(umask 077 && printf 'GITHUB_TOKEN=ghp_%s\n' "$(openssl rand -hex 18)" > .env)
ssh-keygen -q -t ed25519 -N '' -C build-secrets-demo -f deploy_keyFinally, the Dockerfile with all three mistakes. It takes the token as a build argument, copies it into ENV so npm can read it, and copies the whole folder, keys included:
cd ~/build-secrets-demo/app
cat > Dockerfile <<'DOCKER'
FROM node:26-slim
ARG GITHUB_TOKEN
ENV GITHUB_TOKEN=$GITHUB_TOKEN
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
CMD ["node", "server.js"]
DOCKER
ls -AIf you have Docker on this machine, build it and look at what anyone with the image can see. The token goes in from your environment, so it is not typed on the command line, but that does not help once it reaches the image:
cd ~/build-secrets-demo/app
export GITHUB_TOKEN="$(grep '^GITHUB_TOKEN=' .env | cut -d= -f2-)"
docker build --build-arg GITHUB_TOKEN -t secrets-demo:leaky .
docker history --no-trunc secrets-demo:leaky | grep ghp_
docker image inspect --format '{{json .Config.Env}}' secrets-demo:leaky
docker run --rm secrets-demo:leaky ls -A
unset GITHUB_TOKENCheck it worked
ls -A lists .env, .npmrc, Dockerfile, deploy_key, deploy_key.pub, package-lock.json, package.json and server.js. If you built the image: docker history prints lines containing the full ghp_ token, something like ENV GITHUB_TOKEN=ghp_…; docker image inspect shows it in the image's environment list; and docker run … ls -A shows .env and deploy_key inside /app. Deleting them in a later RUN rm step would not help, because the COPY layer still holds them.
Step 3 · Catch the leaks with Trivy before you build
Scan the build context for secrets. --scanners secret runs only the secret scanner, which needs no vulnerability database download, so the scan is quick and light on mobile data. --exit-code 1 makes Trivy fail when it finds something, which is what you want in a script or CI job:
cd ~/build-secrets-demo/app
trivy fs --scanners secret --exit-code 1 . || echo "Trivy exit code: $?"Trivy prints a section for each file with a finding, with the matched text masked. Save the same scan as JSON next to the project (not inside it, or the report becomes part of the build context) and pick out the rule IDs:
cd ~/build-secrets-demo/app
trivy fs --scanners secret --format json --output ../secrets-before.json .
grep '"RuleID": "private-key"' ../secrets-before.json
grep '"RuleID": "github-pat"' ../secrets-before.jsonThe secret scanner looks at file contents. Trivy's config scanner looks at the Dockerfile itself, and its check DS-0031 flags well-known secret names such as GITHUB_TOKEN in ARG and ENV. --severity HIGH,CRITICAL leaves out style advice so only the serious findings show:
cd ~/build-secrets-demo/app
trivy config --severity HIGH,CRITICAL --exit-code 1 . || echo "Trivy exit code: $?"
trivy config --severity HIGH,CRITICAL --format json --output ../config-before.json .
grep -oE '"ID": ?"DS-?0?031"' ../config-before.json | sort -uTwo things to know about the secret scanner. It skips files whose paths look like tests or examples, and Markdown files, to cut false positives; Trivy's secret scanning docs explain how to change that with a trivy-secret.yaml file. And it only finds what matches a rule, so a clean scan is a safety net, not proof that nothing sensitive is there.
Check it worked
Both scans end with Trivy exit code: 1. The secret scan reports deploy_key as an AsymmetricPrivateKey finding (HIGH) and .env as a GitHub personal access token (CRITICAL), and the two grep lines print the private-key and github-pat rule IDs. The config scan reports DS-0031 for GITHUB_TOKEN in both the ARG and the ENV line (it also flags the missing USER line, which the fixed Dockerfile adds).
Step 4 · Move the secrets out and use a secret mount
The fix has three parts: secrets live outside the build context, the Dockerfile asks for a secret instead of an argument, and a .dockerignore file stops stray secrets being sent to the builder if one lands in the folder again.
Move the token and the key into ~/build-secrets-demo/secrets, and write the token on its own into a file for the build. The value goes from one file to the other through a pipe, so it never appears on a command line:
cd ~/build-secrets-demo/app
mv .env deploy_key deploy_key.pub ../secrets/
(umask 077 && grep '^GITHUB_TOKEN=' ../secrets/.env | cut -d= -f2- | tr -d '\n' > ../secrets/github_token)
ls -l ../secrets/With a real token you would rather type it, run (umask 077 && read -rsp 'GitHub token: ' t && printf '%s' "$t" > ~/build-secrets-demo/secrets/github_token); echo and paste it at the prompt.
Now rewrite the Dockerfile. The install step gets two mounts that exist only while that RUN runs:
--mount=type=bind,source=.npmrc,target=/app/.npmrcmakes.npmrcvisible to npm without copying it into a layer. Bind mounts are read-only by default.--mount=type=secret,id=github_token,env=GITHUB_TOKEN,required=truetakes the secret the build was given under the IDgithub_tokenand sets it as theGITHUB_TOKENenvironment variable for this one command, which is what.npmrcreads. Withoutenv=, the secret would be a file at/run/secrets/github_token.required=truemakes the build stop with an error if you forget to pass the secret, instead of carrying on without it.
cd ~/build-secrets-demo/app
cat > Dockerfile <<'DOCKER'
# syntax=docker/dockerfile:1
FROM node:26-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=bind,source=.npmrc,target=/app/.npmrc \
--mount=type=secret,id=github_token,env=GITHUB_TOKEN,required=true \
npm ci --omit=dev
COPY server.js ./
USER node
EXPOSE 3000
CMD ["node", "server.js"]
DOCKER
cat > .dockerignore <<'IGNORE'
.env
.env.*
*.pem
*.key
*_key
*_key.pub
id_*
.git
node_modules
IGNOREThe COPY lines name exact files, so a secret dropped into the folder later is not copied in even if .dockerignore misses it. Keep the .dockerignore anyway: it also stops the file being sent to the builder at all.
Scan again:
cd ~/build-secrets-demo/app
trivy fs --scanners secret --exit-code 1 .
echo "secret scan exit code: $?"
trivy config --severity HIGH,CRITICAL --exit-code 1 .
echo "config scan exit code: $?"Check it worked
ls -l ../secrets/ shows github_token and .env with -rw------- permissions. Both Trivy scans finish without findings, and the two echo lines print exit code 0. If either scan still fails, the output names the file or Dockerfile line to fix.
Step 5 · Build with the secret and check the image
Pass the secret by ID and say where its value comes from. src= reads it from a file; env= reads it from an environment variable instead:
cd ~/build-secrets-demo/app
docker build --secret id=github_token,src="$HOME/build-secrets-demo/secrets/github_token" -t secrets-demo:fixed .
docker history --no-trunc secrets-demo:fixed | grep -c ghp_ || echo "no token in the history"
docker image inspect --format '{{json .Config.Env}}' secrets-demo:fixed
docker run --rm secrets-demo:fixed ls -AThen scan the built image, which reads every file in it, including those your Dockerfile copied in:
trivy image --scanners secret --exit-code 1 secrets-demo:fixedRun the same command against secrets-demo:leaky to see the difference. If an image like leaky was ever pushed to a registry, deleting it is not enough: anyone may already have pulled it. Revoke the token and the key first, then remove the image.
Check it worked
The build finishes. docker history prints 0 then no token in the history. The environment list from docker image inspect has no GITHUB_TOKEN. docker run … ls -A lists package-lock.json, package.json and server.js (and possibly an empty node_modules), with no .env, .npmrc or deploy_key. trivy image reports nothing in /app, while the same scan of secrets-demo:leaky reports the key and the token there. Building without the --secret flag fails at the npm ci step, because of required=true.
Step 6 · Clone a private repository with an SSH mount
For a private Git repository over SSH, do not copy a key in. An SSH mount forwards your SSH agent's socket into one RUN step: the build can use the key the agent holds, but the key itself never enters the build. In your own project, put the deploy key of a private repository you own in place of the throwaway key, and replace <your-org>/<private-repo> below.
The build also needs to trust GitHub's host key. Fetch it once on your machine, compare the fingerprint with GitHub's published list, and commit the file; it holds only public keys:
cd ~/build-secrets-demo/app
ssh-keyscan -t ed25519 github.com > known_hosts
ssh-keygen -lf known_hostsThen add a stage like this to the Dockerfile. required=true makes the step fail clearly if no agent is passed:
FROM debian:trixie-slim AS source
RUN apt-get update \
&& apt-get install -y --no-install-recommends git openssh-client ca-certificates \
&& rm -rf /var/lib/apt/lists/*
COPY known_hosts /root/.ssh/known_hosts
RUN --mount=type=ssh,required=true \
git clone --depth 1 git@github.com:<your-org>/<private-repo>.git /srcA later stage copies what it needs with COPY --from=source /src/<path> <destination>. Start an agent, load the key and pass the agent to the build with --ssh default:
eval "$(ssh-agent -s)"
ssh-add ~/build-secrets-demo/secrets/deploy_key
docker build --ssh default --secret id=github_token,src="$HOME/build-secrets-demo/secrets/github_token" -t secrets-demo:fixed .
ssh-agent -kFor HTTPS clones with a token instead, BuildKit also accepts a secret with the special ID GIT_AUTH_TOKEN when the build context itself is a Git URL; Docker's build secrets guide shows the form.
Check it worked
ssh-keygen -lf known_hosts prints 256 SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU github.com (ED25519), the ED25519 fingerprint on GitHub's SSH key fingerprints page. With your own repository, the clone step finishes and docker history --no-trunc shows the git clone command but no key. Without --ssh default, the build stops at that step with an error about the missing SSH mount.
Step 7 · Pass the secret in Docker Compose
Compose passes build secrets the same way. Declare the secret once at the top level, pointing at the file outside the build context, and list it under the service's build section. With the short syntax, the secret's name is the ID the Dockerfile asks for:
cd ~/build-secrets-demo/app
cat > compose.yaml <<'YAML'
services:
web:
build:
context: .
secrets:
- github_token
ports:
- "8080:3000"
secrets:
github_token:
file: ../secrets/github_token
YAML
grep -n 'github_token' compose.yamlTo read the value from an environment variable on the build machine instead of a file, replace file: ../secrets/github_token with environment: GITHUB_TOKEN. For the SSH stage, add ssh: [default] under build.
cd ~/build-secrets-demo/app
docker compose build
docker compose up -d
curl -s http://localhost:8080
docker compose down --rmi localRuntime secrets are a separate matter: if the running app needs a token, pass it with an env_file or a runtime secret, never by baking it into the image.
Check it worked
grep prints three numbered lines: - github_token under build.secrets, the top-level github_token: entry and its file: ../secrets/github_token path. None of them holds the token itself. docker compose build finishes, curl prints secrets demo, and the image passes the same docker history check as before.
Step 8 · Build with secrets in GitHub Actions
In CI, the token comes from the platform's secret store. The secrets input of docker/build-push-action turns each id=value line into a build secret, so the Dockerfile does not change. This workflow scans the build context with the Trivy image first, so a key committed by mistake fails the job before anything is built. Save it as .github/workflows/image.yml in a repository that contains the app folder:
name: image
on: push
permissions:
contents: read
packages: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Scan the build context for secrets
run: docker run --rm -v "$PWD/app:/src:ro" aquasec/trivy:0.76.2 fs --scanners secret --exit-code 1 /src
- uses: docker/setup-buildx-action@v4
- uses: docker/build-push-action@v7
with:
context: app
push: false
tags: secrets-demo:ci
secrets: |
"github_token=${{ secrets.GITHUB_TOKEN }}"The built-in GITHUB_TOKEN with packages: read can read GitHub Packages that belong to the same repository, or packages whose settings grant this repository access; it cannot read any other @your-org package. For a token of your own, add it under Settings → Secrets and variables → Actions and use ${{ secrets.YOUR_NAME }} instead. The action also has secret-envs and secret-files inputs for values already in an environment variable or file on the runner.
The scan step needs no secrets, so you can run the same line on your laptop as a pre-push check:
cd ~/build-secrets-demo
docker run --rm -v "$PWD/app:/src:ro" aquasec/trivy:0.76.2 fs --scanners secret --exit-code 1 /srcCheck it worked
Push a commit. In the run's log, the scan step ends without findings and the build step shows the npm ci step finishing. Add a file holding a dummy private key to app/ in a branch and push it: the scan step fails, the build step does not run, and the log names the file.
Step 9 · Clean up
Remove the images and the demo folder, which holds the throwaway key and the made-up token:
docker rmi secrets-demo:leaky secrets-demo:fixedrm -rf ~/build-secrets-demoTrivy stays installed in /usr/local/bin. Remove it with sudo rm /usr/local/bin/trivy if you no longer need it, and rm -rf ~/.cache/trivy for its cached checks.
Check it worked
ls ~/build-secrets-demo reports No such file or directory, and docker images secrets-demo lists nothing.
Next steps
- Keep the same token and key out of your repository history too: keep secrets out of Git.
- Make the fixed build fast as well as safe, with cache mounts next to the secret mount: speed up Docker builds with layer caching and cache mounts.
- Use Trivy on the finished image for vulnerable packages as well as secrets: scan container images for vulnerabilities with Trivy.
Related tutorials
- Validate Kubernetes manifests before they reach a clusterYou will have one script that checks plain, Kustomize, Helm, generated and custom-resource manifests against the Kubernetes 1.37 schemas and a set of lint rules, with no cluster, and a GitHub Actions job that runs it on every pull request.
- Store data in Kubernetes with persistent volumes and claimsYou will claim storage on a Kubernetes 1.37 kind cluster, prove the data outlives its pod, see which access modes and reclaim policies keep or lose data, and know how expansion and snapshots work on a cloud CSI driver.
- Sign and verify container images with cosignYou will sign an image by digest with a password-protected cosign key, prove the signature verifies and that tampering fails, attach a signed SBOM attestation, and have a GitHub Actions workflow ready that signs keylessly through Sigstore.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials