5.1.2.4 Dockerignore Secrets
A focused guide to Dockerignore Secrets, connecting core concepts with practical Docker and container operations.
Excluding secrets through .dockerignore prevents sensitive files — .env files, private keys, credentials — from ever being included in the build context in the first place, closing off one of the most common and consequential ways secrets accidentally end up baked into a built image.
What Commonly Needs Excluding
Most projects accumulate at least a few files containing sensitive values during local development, which should never be transferred to a build context that might ultimately produce a widely distributed image.
.env
.env.*
*.pem
*.key
secrets/
credentials.json
Why This Matters More Than It Might First Appear
Even if a Dockerfile itself never explicitly COPYs a secret file, a broad COPY . . instruction would still include it unless .dockerignore excludes it first — the danger here is not deliberate exposure but accidental inclusion through an overly broad copy operation.
COPY . .
Without a .dockerignore excluding .env, this single broad instruction silently bakes that file's contents into the image, retrievable by anyone with access to it later.
Verifying Secrets Are Actually Excluded
Confirming that sensitive files are genuinely excluded, rather than assuming the .dockerignore is working correctly, is worth doing explicitly before considering a project's configuration complete.
docker build -t myapp .
docker run --rm myapp find / -name ".env" 2>/dev/null
An empty result here confirms the exclusion is actually taking effect as intended.
Defense in Depth Beyond .dockerignore Alone
Excluding secrets from the build context is a strong first line of defense, but pairing it with secret-scanning tools in CI provides an additional, independent check in case a .dockerignore exclusion is ever accidentally removed or misconfigured.
docker scan myapp:1.0
Why Excluding Secrets Matters
A .dockerignore that reliably excludes sensitive files is one of the simplest, most important safeguards against a serious and entirely avoidable category of security incident: secrets permanently and silently baked into a distributed image.