DEV Community

hao li
hao li

Posted on

Your .gitignore Won't Save Your Docker Image

Your .gitignore Won't Save Your Docker Image

Here's a scenario: your repo has a solid .gitignore. .env is ignored, keys are ignored, terraform.tfstate is ignored. Git is clean. Then you docker build, push the image to a registry, and... your .env is sitting inside the image. Anyone who pulls it can read your secrets.

The build context is its own attack surface. .gitignore controls what goes into git. What goes into your image is controlled by a different file with subtly different rules: .dockerignore. And the difference is invisible until something ships that shouldn't have.

What I built

contextleak — a zero-dependency Python CLI that verifies what your .dockerignore actually does:

  1. Parses every COPY/ADD in your Dockerfile (multi-stage aware — COPY --from=builder copies come from another stage, not the context, so they're skipped).
  2. Simulates .dockerignore matching with Docker's real semantics: patterns anchored to the context root, ** crossing directories, ! negation with last-match-wins, directory patterns excluding their contents.
  3. Expands each COPY/ADD source glob against the files that would actually be sent to the daemon.
  4. Flags the sensitive names: .env/.env.*, *.pem/*.key, SSH private keys, *credential*, *secret*, *token*, .npmrc, .pypirc, Terraform state and *.tfvars, kubeconfigs, service-account files, and the .git directory.
pip install contextleak
cd your-project
contextleak
Enter fullscreen mode Exit fullscreen mode
Scanned 214 files in build context (12 excluded by .dockerignore), 4 COPY/ADD instruction(s).

LEAK: 2 instruction(s) would copy sensitive files:

  [COPY line 8] COPY . /app  (stage: stage-1)
    - .env  (environment file, usually holds secrets)
    - certs/server.key  (private key material)
Enter fullscreen mode Exit fullscreen mode

Exit code 1 on leak, 0 when clean — so it drops straight into CI. --json gives machine-readable output.

It also warns when an instruction references files your .dockerignore removed — that's a build that fails or silently copies nothing, which is its own class of bug.

Why not just use Trivy?

Trivy and friends scan the finished image for known vulnerabilities — CVEs in your base image and packages. That's important, but it's a different layer. A leaked secret has no CVE. If your .env gets COPY'd in at build time, it ships with every push of that image, and no vulnerability scanner will flag it because it's your file, not a known-vulnerable package.

contextleak checks the layer scanners can't see: the build context itself. One cut, one job — does your build context leak secrets into the image? Nothing else.

Try it

pip install contextleak and run it against your own projects — I'd genuinely like to hear what it finds. If it catches a real leak in your repo, tell me in the comments.

Top comments (0)