TL;DR: Docker secrets handling is only safe when teams keep credentials out of images, layers, and environment variables, and GitGuardian cites a 2021 finding that 7% of Docker Hub images contained at least one secret. The real control gap is not containerization itself but how build-time and runtime secret exposure is governed.
At a glance
What this is: This is an operational guide to keeping Docker credentials out of images, Dockerfiles, and runtime leakage paths, with the central finding that image-layer exposure remains a live supply-chain risk.
Why it matters: It matters to IAM and NHI practitioners because container secrets are non-human credentials, and if they are embedded, copied, or logged, access governance fails before runtime controls even start.
By the numbers:
- 7% of the Docker Hub images contained at least one secret in 2021.
- 28.65 million new hardcoded secrets were detected in public GitHub commits in 2025 alone, a 34% year-over-year increase and the largest single-year jump ever recorded.
- 64% of valid secrets leaked in 2022 are still valid and exploitable today, proving that detection alone is not enough without automated revocation.
👉 Read GitGuardian's guide to managing secrets in Docker
Context
Docker secrets management is a governance problem as much as a deployment problem. Container images are often treated as disposable artefacts, but they can carry credentials through layers, build steps, environment variables, and mounted files if teams do not separate build-time access from runtime access. For NHI governance, the issue is straightforward: a secret is still a credential, even when it lives inside a container workflow.
The article focuses on practical controls such as Docker Secrets, Compose secret mounts, SOPS, sidecar injection, BuildKit secret mounts, and image scanning. That is a typical starting point for teams trying to move from ad hoc credential handling to more disciplined NHI control. What is less typical is assuming one mechanism solves the whole problem, because the exposure surface changes between build, deploy, and runtime.
Key questions
Q: How should security teams manage secrets in Docker images?
A: Teams should keep secrets out of image layers entirely, use build-time secret mounts for any authentication needed during builds, and prefer file-based secret delivery at runtime. Image scanning should confirm that no credentials were copied in by mistake. If a secret is discovered, revoke it immediately rather than treating it as a benign finding.
Q: When are environment variables acceptable for container secrets?
A: Environment variables are acceptable only for low-risk, short-lived use cases where the exposure impact is limited and the value is not reused elsewhere. For production credentials, they are too easy to expose through logs, process inspection, and debug tooling. File mounts or external secret stores are the safer default for sensitive NHIs.
Q: What is the difference between Docker Secrets and BuildKit secret mounts?
A: Docker Secrets are primarily a runtime secret delivery mechanism for services, while BuildKit secret mounts are for build-time access without persisting credentials in the image. They solve different parts of the lifecycle. Mature programmes usually need both, because build-time leakage and runtime exposure are separate governance problems.
Q: Should organisations scan Docker images for secrets if they already secure the source code?
A: Yes. Source-code controls do not cover inherited layers, copied files, or secrets that entered through a parent image. Image scanning verifies what actually ships, not just what the repository contains. In practice, it is one of the few controls that can surface credential residue after the build has completed.
Technical breakdown
Why build-layer secret exposure persists in Docker images
Docker images are layered, so anything written during build can remain recoverable even if it is later deleted in the same Dockerfile. Build arguments, shell history inside RUN steps, copied config files, and cached layers can all preserve secrets. BuildKit's secret mount changes the access pattern by making a secret available only to the build step that needs it, rather than baking it into the image. That reduces persistence, but it does not remove the need to control who can build, inspect, or pull the resulting artefact. The same logic applies to base images pulled from registries: inherited layers can still contain latent credentials.
Practical implication: Treat image builds as a privileged secret-handling zone and use secret mounts, not inline values, for any build-time authentication.
File mounts versus environment variables for container secrets
File-based secret mounts are safer than environment variables because they reduce accidental exposure through process listings, debugging output, and container inspection. A file mount also makes the access path more explicit to the application, which helps separate secret retrieval from application configuration. Environment variables remain convenient for development, but convenience is not a security control. In higher-risk environments, the better pattern is to mount a secret file, read it at startup, and keep the value out of logs and shell history. If a workload truly needs env vars, they should be ephemeral and sourced from an encrypted secret store at the last possible moment.
Practical implication: Prefer file-based secret consumption and reserve environment variables for low-risk, short-lived cases with strong logging discipline.
Why scanning images is still necessary after better secret handling
Preventive controls reduce exposure, but they do not eliminate inherited risk from old layers, copied artefacts, or third-party base images. Image scanning catches secrets that have already slipped into a build pipeline, whether they came from a Dockerfile, a copied .env file, or a parent image. This is especially important in supply chains where teams pull public images and reuse them without full provenance review. Secret scanning should therefore be treated as a verification control, not a substitute for secure design. The purpose is to find what policy and process failed to prevent.
Practical implication: Add secret scanning to CI/CD and registry workflows so exposed credentials are detected before images are promoted.
Threat narrative
Attacker objective: Use exposed container secrets to gain durable non-human access across build, deploy, or application dependencies.
- Entry via a hard-coded credential in a Dockerfile, Compose file, or copied environment file that enters the build pipeline.
- Escalation through recovery of secrets from image layers, container inspection, logs, or inherited base images.
- Impact when the exposed NHI credential is reused for repository access, infrastructure access, or downstream API calls.
Breaches seen in the wild
- Shai Hulud npm malware campaign — Shai Hulud campaign: npm malware exposed secrets on GitHub.
- Reviewdog GitHub Action supply chain attack — reviewdog/action-setup GitHub Action supply chain attack exposed secrets.
Read our 52 NHI Breaches Analysis report for a comprehensive view of breaches impacting Non-Human Identities including AI Agents.
NHI Mgmt Group analysis
Image-layer secrecy is the real Docker governance problem. The article is framed as Docker hygiene, but the larger issue is NHI lifecycle control. If a credential enters a build layer, a registry, or a shared Compose file, it has already escaped the intended trust boundary. That makes image provenance, secret scanning, and revocation part of the same control plane, not separate tasks. Practitioners should govern Docker secrets as lifecycle assets, not configuration conveniences.
Ephemeral credential trust debt: Docker teams often reduce exposure at one stage while leaving the credential valid far longer than the container that used it. That creates trust debt, where detection happens after the secret has already been copied into logs, layers, or downstream systems. The practical lesson is to pair secret minimisation with short TTLs and automated revocation, because concealment alone does not neutralise reuse risk. Practitioners should assume any exposed container secret may already have propagated.
Environment variables are configuration, not containment. Moving a secret from a Dockerfile into an environment variable improves convenience but does not create meaningful isolation. The value is still recoverable through common operational tooling, and that makes env vars a weak default for high-value NHIs. Teams should reserve them for low-sensitivity use cases and prefer file mounts or external secret stores for anything that grants infrastructure or production access. Practitioners should classify env vars as transitional, not authoritative, secret delivery.
Secret scanning belongs in the delivery pipeline, not just in source control. The article correctly points to image scanning, and that is where many programmes still underinvest. Docker images are execution artefacts, which means the secrets problem extends beyond code review into build provenance, registry hygiene, and runtime inspection. NHI governance has to follow the credential wherever it travels, especially across containers, base images, and reusable templates. Practitioners should make image scanning a release gate, not a forensic afterthought.
From our research:
- 64% of valid secrets leaked in 2022 are still valid and exploitable today, according to the State of Secrets Sprawl 2026.
- In the same research, 28% of secrets incidents now originate outside code repositories, in Slack, Jira, and Confluence, showing that container hygiene is only one part of the exposure problem.
- For the broader lifecycle view, see Guide to the Secret Sprawl Challenge for how exposure, rotation, and revocation should be handled together.
What this signals
Secret sprawl in container pipelines is becoming a lifecycle problem, not a point-in-time hygiene issue. As more teams shift credentials between source, build, registry, and runtime, the governance question becomes whether the secret remains valid after each transition. That is the real control gap for NHI programmes, and it is why scanning and revocation need to be designed as one workflow.
The practical signal for security teams is that image review must sit alongside access review and release gating. A container that looks clean at build time can still carry inherited risk from base layers or downstream reuse, so the security programme has to inspect artefacts, not assumptions. That is especially important when build systems and CI/CD runners are themselves high-value NHIs.
The next stage is stricter runtime partitioning, with secret delivery tied to specific workload identity, limited duration, and explicit ownership. Teams that still treat Docker secrets as a convenience feature will keep seeing the same gap between policy and practice. The control model now has to account for where the credential exists, who can retrieve it, and how fast it can be revoked.
For practitioners
- Ban hard-coded secrets in build artefacts Prevent credentials from appearing in Dockerfiles, Compose files, copied .env files, and build arguments. Require peer review for any change that touches secret material and block merges when a secret token pattern is detected.
- Use BuildKit secret mounts for build-time access Replace inline credentials with BuildKit secret mounts whenever a build step must reach a private registry, package source, or API. Keep the secret available only to the single step that needs it and avoid writing it to disk inside the image.
- Prefer file mounts over environment variables Mount secrets as files and have the application read them at startup, rather than placing them in process environment. Reserve environment variables for low-risk development workflows and ensure they are never printed in debug output or logs.
- Scan every image before promotion Integrate secret scanning into CI/CD and registry promotion checks so inherited layers, copied files, and base images are inspected before release. Treat any discovered secret as a revocation event, not just a cleanup task.
- Automate revocation after exposure If a secret is found in an image, rotate the credential immediately and invalidate any related tokens, certificates, or API keys. Detection without revocation leaves the same non-human identity usable after exposure.
Key takeaways
- Docker secret handling fails when credentials are allowed to persist in build layers, images, or logs.
- Secret scanning is necessary because secure design alone does not catch inherited or copied credentials.
- For NHI governance, the decisive control is not concealment but short-lived access and rapid revocation.
Standards & Framework Alignment
This section maps relevant standards and security frameworks to the operational risks and controls described in this guidance.
OWASP Non-Human Identity Top 10 address the attack and risk surface, while NIST CSF 2.0 and NIST AI RMF set the governance and control requirements practitioners need to meet.
| Framework | Control / Reference | Relevance |
|---|---|---|
| OWASP Non-Human Identity Top 10 | NHI-03 | Docker secrets rotation and exposure map directly to secret lifecycle controls. |
| NIST CSF 2.0 | PR.AC-1 | Container secrets need access restrictions tied to the workload that consumes them. |
| NIST AI RMF | Automated build and deployment workflows need accountable governance for secret handling. |
Assign explicit ownership for secret injection, scanning, and revocation across the pipeline.
Key terms
- Docker Secret: A Docker Secret is a managed credential stored and delivered to a container without placing the value in the image or plaintext configuration. In practice, it reduces casual exposure during deployment, but it still requires strict access scoping, revocation, and pipeline hygiene to be effective.
- BuildKit secret mount: A BuildKit secret mount is a build-time mechanism that exposes a credential only to the specific step that needs it. It helps prevent secrets from being written into image layers, but it does not replace governance over who can build, inspect, or publish the resulting artefact.
- Secret sprawl: Secret sprawl is the uncontrolled spread of credentials across code, pipelines, logs, documents, and runtime artefacts. It creates hidden non-human identity risk because the same secret may exist in multiple places, making detection, rotation, and revocation harder than policy assumes.
- Image-layer residue: Image-layer residue is sensitive data that remains recoverable from earlier Docker layers even after a later step deletes it. It is a common failure mode in container security because the final image can look clean while still containing extractable secrets in its history.
What's in the full article
GitGuardian's full blog post covers the operational detail this post intentionally leaves for the source:
- Step-by-step Docker Secrets and Swarm examples for creating and mounting secrets at runtime.
- Compose file patterns for file-based secret delivery and external secret references.
- BuildKit secret mount syntax for build-time authentication without persisting credentials in layers.
- Secret scanning examples for Docker images, including checks against inherited base-image exposure.
👉 GitGuardian's full post covers Docker Secrets, BuildKit, Compose, and image-scanning examples.
Deepen your knowledge
Secrets management in Docker and build-layer credential control are core topics in our NHI Foundation Level course, the industry's only accredited NHI security programme. If your team is working through containerised workloads and CI/CD exposure, it is worth exploring.
Published by the NHIMG editorial team on 2025-08-27.
NHI Mgmt Group — the independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org