TL;DR: Docker secrets handling varies sharply across build, local, and production environments, and the article shows why image layers, environment variables, and ad hoc files each create different exposure paths, according to Infisical. The underlying lesson is that container secrecy fails when teams treat runtime credentials like static configuration.
At a glance
What this is: The article explains how Docker secrets should be handled differently across build, local development, single-host production, and Swarm deployments to avoid baking credentials into images or exposing them at runtime.
Why it matters: It matters because IAM and platform teams need secrets controls that survive container lifecycle changes, reduce secret sprawl, and keep build-time, runtime, and cluster distribution aligned.
By the numbers:
- When AWS credentials are exposed publicly, attackers attempt access within an average of 17 minutes and as quickly as 9 minutes in some cases.
👉 Read Infisical's guide to managing secrets across Docker build, Compose, and Swarm
Context
Docker secrets management becomes fragile when teams move from a single developer machine to build pipelines and multi-node clusters. In that shift, the core problem is not just where a secret lives, but whether the platform leaks it through image history, environment variables, or uncontrolled file handling.
For IAM and DevSecOps teams, this is a lifecycle problem as much as a tooling problem. Build-time secrets, runtime secrets, and cluster-distributed secrets each need different controls, and the right pattern changes as the deployment model changes.
The article’s practical value is in showing how container secrecy should map to the Docker context rather than to a one-size-fits-all rule. That is typical of modern NHI governance problems: the control surface changes as fast as the workload does.
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: Why do environment variables create risk in containerised runtimes?
A: Environment variables are easy to pass, but they are visible to inspection commands, inherited by child processes, and sometimes exposed in logs. For anything sensitive, file-mounted secrets or orchestration-native secrets reduce the number of places a credential can leak from.
Q: When should teams prefer Docker Compose secrets over .env files?
A: Prefer Compose secrets when a container needs runtime credentials but the team wants to avoid plaintext files on disk. A .env file is simple, but it increases the chance of accidental commits, host exposure, and inconsistent handling across environments.
Q: What should organisations do before moving container secrets into production?
A: Map each secret to its lifecycle stage, then decide whether build-time, runtime, or cluster-distributed handling is required. That prevents teams from reusing the same exposure pattern everywhere, which is how container secret sprawl usually starts.
Technical breakdown
Why Docker image layers can permanently expose build secrets
Docker images are layered artifacts, so anything passed through traditional build arguments or environment variables can be preserved in build history. If a secret is used during compilation, it may remain recoverable through image inspection even after later steps remove it from the final filesystem view. BuildKit secret mounts change that pattern by exposing the credential only during the build step and not committing it into the resulting layer. This is the difference between transient use and persistent disclosure.
Practical implication: use secret mounts for build-time authentication and stop passing credentials through ARG or ENV in image builds.
Why runtime environment variables are weaker than file-mounted secrets
Runtime environment variables are convenient, but they are not private storage. Tools such as docker inspect, logs, child processes, and host-side monitoring can reveal them, which makes them a poor choice for secrets that need to survive beyond a single process boundary. Docker Compose and similar mechanisms can instead inject secrets as files, which limits exposure to the container process that needs them. This is not a cosmetic difference. It materially changes the visibility of the credential to the host and adjacent tooling.
Practical implication: prefer file-mounted secrets over plain environment variables for any container that handles database passwords, API keys, or tokens.
How Swarm secrets reduce distribution risk across multiple nodes
In a multi-node Docker Swarm environment, the main challenge is not just confidentiality but coordinated distribution. A secret has to be available to the right replicas without being written to disk on every node or copied into ad hoc configuration files. Swarm’s native Secrets API addresses that by distributing the secret to containers as needed. That model fits clustered workloads better than local environment files because it keeps the distribution mechanism inside the orchestration layer rather than outside it.
Practical implication: use orchestration-native secrets for clustered production workloads instead of copying credentials through shared files or manual node configuration.
Threat narrative
Attacker objective: The attacker aims to recover reusable credentials that unlock build pipelines, container access, or backend services.
- Entry via hardcoded or build-time secrets occurs when credentials are embedded into Docker image layers, plaintext environment files, or command history.
- Escalation follows when an attacker or unauthorized operator can inspect images, read host-visible environment variables, or access distributed configuration on multiple nodes.
- Impact is credential reuse across container build and runtime paths, which can expose private registries, databases, and downstream systems that trust the same secret.
Breaches seen in the wild
- Reviewdog GitHub Action supply chain attack — reviewdog/action-setup GitHub Action supply chain attack exposed secrets.
- CI/CD pipeline exploitation case study — full server takeover via exposed .git directory and mismanaged CI/CD pipeline 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
Secret exposure in Docker is a lifecycle failure, not just a build mistake. The same credential can be exposed at build time, runtime, or cluster distribution time, and each stage requires different handling. The article shows that teams often solve one stage while leaving the others exposed, which is why isolated point controls do not solve container secrecy. Practitioners should treat Docker secrets as a lifecycle governed asset, not a deployment convenience.
Image leakage remains the most durable form of container secret exposure. Once a secret is baked into a layer, the image itself becomes an evidence trail that outlives remediation. That is why build-time handling must be designed around transient secret mounts rather than cleanup after the fact. The practitioner conclusion is simple: if the image can be pulled, the secret can be recovered unless it was never committed.
Runtime environment variables create an identity visibility gap. The secret may be intended for one process, but the host and surrounding tooling can still observe it. That is a governance problem because access is broader than the application owner assumes. The implication for IAM and platform teams is that credential distribution must be scoped to the container boundary, not the machine boundary.
Multi-node orchestration turns secret distribution into an NHI governance problem. In Swarm and similar systems, the question is no longer only how to store the credential, but how to distribute it without creating copy-based sprawl across nodes. This is where centralized lifecycle control matters most. The practitioner takeaway is that cluster-native secrets should be managed as governed non-human identities, with rotation and offboarding tied to workload lifecycle.
The named concept here is container credential drift: the gap between where a secret is created, where it is exposed, and where it is still trusted. Docker environments amplify that drift because build, test, and production each use different delivery patterns. Once drift exists, rotation becomes inconsistent and auditability weakens. The practical conclusion is that teams must model secrets by environment boundary, not by repository or deployment convenience.
From our research:
- When AWS credentials are exposed publicly, attackers attempt access within an average of 17 minutes and as quickly as 9 minutes in some cases, according to LLMjacking: How Attackers Hijack AI Using Compromised NHIs.
- From our research: The average estimated time to remediate a leaked secret is 27 days, despite 75% of organisations expressing strong confidence in their secrets management capabilities, according to The State of Secrets in AppSec.
- From our research: Read NHI Lifecycle Management Guide for the provisioning, rotation, and offboarding patterns that reduce long-lived secret exposure.
What this signals
Container secret handling is increasingly a lifecycle discipline, not a deployment preference. Build-time, runtime, and orchestration-time controls need to be evaluated separately because each one fails differently. Teams that still rely on one pattern across all environments will continue to accumulate secret sprawl, especially when container turnover is faster than credential rotation.
Secret exposure windows are narrowing for attackers, but not for defenders. If exposed credentials are abused within minutes, as our research on LLMjacking shows, then rotation, revocation, and runtime injection need to be operationally ready before deployment. The programme signal is clear: the faster the workload moves, the less tolerance there is for manual secret handling.
Container credential drift is the pattern to watch: the same secret appears in a build pipeline, a compose file, and a production cluster, but governance assumptions differ at each layer. That is exactly where IAM, PAM, and secrets management programmes need tighter ownership boundaries, or the platform will keep outpacing the controls.
For practitioners
- Use BuildKit secret mounts for image builds Pass private registry tokens through BuildKit mounts so the credential is available only during the build step and never persists in image layers or history.
- Replace plaintext environment variables with file-mounted secrets For runtime containers, inject database passwords and API keys as mounted files instead of -e flags, because host tools and logs can expose environment variables.
- Centralize secret sourcing before Docker execution Use a single secret manager as the source of truth for build, Compose, and Swarm workflows so the same credential is not copied into .env files or repository secrets.
- Align secret rotation with container lifecycle Rotate build and runtime credentials on a schedule that matches image rebuilds, container replacement, and cluster redeployment so stale copies do not persist across environments.
Key takeaways
- Docker secrets fail when teams treat build, runtime, and cluster handling as the same problem.
- Image layers and environment variables create persistent exposure paths that file-mounted and orchestration-native secrets can reduce.
- Container governance improves when secrets are managed as lifecycle assets with distinct controls for each deployment stage.
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, NIST SP 800-53 Rev 5 and NIST Zero Trust (SP 800-207) set the governance and control requirements practitioners need to meet.
| Framework | Control / Reference | Relevance |
|---|---|---|
| OWASP Non-Human Identity Top 10 | NHI-03 | The article centres on hardcoded, runtime, and distributed secret exposure. |
| NIST CSF 2.0 | PR.AC-1 | Secret access and distribution map to access control in container workflows. |
| NIST SP 800-53 Rev 5 | IA-5 | Authenticator management is directly relevant to token and password handling. |
| NIST Zero Trust (SP 800-207) | The article aligns with continuous verification and minimised trust for runtime secrets. |
Limit secret access to the container process and verify distribution paths at each deployment stage.
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.
- Container Credential Drift: Container credential drift is the gap between where a secret is created, where it is exposed, and where it is still trusted. It appears when build pipelines, local workflows, and production clusters all handle the same credential differently, making rotation and auditability harder.
- Orchestration-Native Secret Distribution: Orchestration-native secret distribution means the platform, not ad hoc scripts or files, handles how secrets reach running workloads. For clustered containers, this limits replication of sensitive values and keeps distribution closer to the workload lifecycle instead of the host filesystem.
What's in the full article
Infisical's full blog post covers the operational detail this post intentionally leaves for the source:
- Step-by-step Dockerfile and Compose examples for handling build-time and runtime secrets
- Practical CLI commands for injecting secrets into local development and GitHub Actions workflows
- A full Swarm deployment pattern showing how cluster-managed secrets differ from single-host handling
- Implementation notes for mapping one secret strategy across development, test, and production
Deepen your knowledge
NHI governance, agentic AI identity, and machine identity lifecycle are core topics in our NHI Foundation Level course, the industry's only accredited NHI security programme. If you are building or maturing an IAM programme, it is worth exploring.
Published by the NHIMG editorial team on July 30, 2026.
NHI Mgmt Group — the independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org