# NEVER do this:ENV DATABASE_URL=postgres://user:pass@host/db
COPY.env/app/.env
Example
# Bad - secret is in the image layer history:ENV API_KEY=sk-abc123...# Fix - pass secrets at runtime:docker run -e API_KEY=sk-abc123 myapp:1.0docker run --env-file.env myapp:1.0# For build-time secrets (e.g., private npm token):docker build --secret id=npmrc,src=.npmrc.# In Dockerfile:RUN--mount=type=secret,id=npmrc,target=/root/.npmrcnpm ci
Note ENV values and COPYed files are permanently visible via docker history and docker inspect. Even if you delete them in a later layer, they exist in the previous layer. Use --secret mounts for build-time secrets and runtime env vars or secret managers for runtime secrets.
git filter-repo --invert-paths--path<secret-file># Then: rotate the credential immediately
Example
# Step 1: ROTATE THE SECRET IMMEDIATELY# (It's in the remote history even if you delete it)# Step 2: Remove from all history:pip install git-filter-repo
git filter-repo --invert-paths--path.env# Step 3: Force push the rewritten history:git push --force--all# Step 4: Tell all collaborators to re-clone
Note CRITICAL: Even if you delete the file in a new commit, the secret is still in the Git history and anyone can find it. The FIRST thing to do is rotate/revoke the compromised credential. Rewriting history with filter-repo is step two. GitHub also has a 'secret scanning' feature that alerts you.
Frequently asked questions
How does Docker handle leaked credential?
This task is covered in 2 stacks on this page: Docker, Git. The "Baking Secrets into Images" snippet in Docker uses `# NEVER do this:`.
Which command does the Docker example use?
The "Baking Secrets into Images" snippet uses `# NEVER do this:`, from the Common Mistakes section of the Docker cheat sheet.
Which stacks cover "leaked credential" on this page?
Docker, Git. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Baking Secrets into Images": ENV values and COPYed files are permanently visible via docker history and docker inspect. Even if you delete them in a later layer, they exist in the previous layer. Use --secret mounts for build-time secrets and runtime env vars or secret managers for runtime secrets.