Skip to content
Hands-on IT IT Drills

Day 12: .env, .gitignore and .dockerignore – the Triangle

Goal: Keep the .env out of Git and the build context, cleanly remove a key that was already committed, and understand how Compose reads the .env. · Duration: approx. 75 min · Prerequisite: Day 11

Briefing

  • .env holds local values, including secrets. It stays on your machine.
  • .env.example lists all variables without values and goes into the repository.
  • .gitignore keeps the .env out of Git, .dockerignore out of the build context. Same intent, different pattern syntax.
  • Compose reads the .env by itself, but only for ${…} in compose.yaml. It only gets into the container via env_file:.
                     .env  (local, never commit)
                  ┌────────────┼──────────────┐
             .gitignore     Compose:       .dockerignore
           not in the repo  ${…} and       not in the context
                            env_file:
                  └────────────┼──────────────┘
              .env.example  (names without values, into the repo)

Drill 1: A repository for notes

source ~/docker-lab/setup/env.sh
mkdir -p ~/docker-lab/tag12 && cd ~/docker-lab/tag12
cp -R "$LAB/code/notes/." . && cp -R "$LAB/code/tag11/notes/." .

The second copy lays the state from the end of Day 11 on top – even if you skipped it. So far notes wasn’t a Git repository. That changes now:

git init -b main
git status --short

Expected:

Initialized empty Git repository in /Users/du/docker-lab/tag12/.git/
?? .dockerignore
?? .env
?? .env.example
?? .hadolint.yaml
?? README.md
?? notes-api/
?? notes-web/
?? notes-worker/

To Git, the .env is a file like any other. There is no .gitignore yet.

Security: The repository stays local. No git remote add, no push – not even to a private repository.

Save your progress? Sign up for free

Drill 2: The classic – .env in the first commit

git add .
git commit -q -m "notes: erster Stand"
git show --name-only --format= HEAD | grep env

Expected:

.env
.env.example

That’s how almost every secret incident in Git begins: git add . in the first commit, before anyone thought of a .gitignore.

Save your progress? Sign up for free

Drill 3: .gitignore – and why it doesn’t help now

cat > .gitignore <<'EOF'
# .gitignore – what never belongs in the repository (Day 12)
# Secrets and local values (.env.example is the template and may go in)
*.env
.env
.env.*
!.env.example
*.pem
*.key
secrets/
.npmrc
# Dependencies and build artifacts
node_modules/
dist/
.venv/
__pycache__/
*.pyc
*.test
# Operating system and editor
.DS_Store
EOF
git status --short
git check-ignore -v .env; echo "Exit-Code: $?"

Expected:

?? .gitignore
Exit-Code: 1

git status shows no change to the .env, and check-ignore says “not ignored”. Why? .gitignore only affects files that Git does not track yet. The .env has been in the index since Drill 2. Whether the rule matches in principle is revealed by --no-index, and which tracked files would actually be ignored is shown by ls-files:

git check-ignore -v --no-index .env
git ls-files --cached --ignored --exclude-standard

Expected:

.gitignore:4:.env   .env
.env

The second line is your cleanup list. In someone else’s repository, this is the fastest health check.

Save your progress? Sign up for free

Drill 4: Clean up, history, rotate

git rm --cached .env
git add .gitignore
git status --short
git commit -q -m "chore: .env raus, .gitignore rein"
ls .env

Expected:

rm '.env'
D  .env
A  .gitignore
.env

--cached only removes the file from the index; your working copy stays. Is the key gone from Git now?

git log --oneline -- .env
git log -S lab-api-key-123 --format='%h %s'
git show HEAD~1:.env

Expected (hashes differ):

a78d05a chore: .env raus, .gitignore rein
ac09be7 notes: erster Stand
a78d05a chore: .env raus, .gitignore rein
ac09be7 notes: erster Stand
# Lokale Entwicklungswerte – Lab-Werte, niemals produktiv verwenden
NOTES_API_KEY=lab-api-key-123

No. git log -S finds every commit that changes the number of occurrences: the one that brought the key and the one that removed it. Every clone contains both. That’s why the order is: rotate first, then clean up the history.

cat > .env <<'EOF'
# Lokale Entwicklungswerte – Lab-Werte, niemals produktiv verwenden
NOTES_API_KEY=lab-api-key-456
EOF
git status --short

Expected: no output. The new .env is ignored, the old key is worthless.

Warning: git filter-repo (a separate tool) can rewrite the history, for example with git filter-repo --invert-paths --path .env. That changes all commit hashes; afterwards everyone has to re-clone, and forks and caches of the Git platform still keep the key. Rotating is never optional.

Save your progress? Sign up for free

Drill 5: Check patterns instead of guessing

Create a few typical candidates and ask Git which rule applies:

mkdir -p secrets notes-web/node_modules/demo notes-web/dist
printf '%s\n' lab-api-key-456 > secrets/notes_api_key.txt
touch .env.local lab.env notes-web/.npmrc notes-web/dist/app.js \
  notes-web/node_modules/demo/index.js notes-api/notes-api.test
git check-ignore -v .env .env.local lab.env secrets/notes_api_key.txt \
  notes-web/.npmrc notes-web/dist/app.js notes-api/notes-api.test notes-api/main.go

Expected:

.gitignore:4:.env   .env
.gitignore:5:.env.* .env.local
.gitignore:3:*.env  lab.env
.gitignore:9:secrets/   secrets/notes_api_key.txt
.gitignore:10:.npmrc    notes-web/.npmrc
.gitignore:13:dist/ notes-web/dist/app.js
.gitignore:17:*.test    notes-api/notes-api.test

main.go is missing from the list: not ignored. Patterns without a / in the middle apply at any depth, so notes-web/.npmrc matches .npmrc. The overall picture comes from:

git status --short --ignored

Expected:

!! .env
!! .env.local
!! lab.env
!! notes-api/notes-api.test
!! notes-web/.npmrc
!! notes-web/dist/
!! notes-web/node_modules/
!! secrets/

Two traps. First, the exception !.env.example: with -v, check-ignore also reports negated matches and then exits with 0, even though the file is not ignored. In scripts you use -q:

git check-ignore -v --no-index .env.example; echo "Exit-Code: $?"
git check-ignore -q --no-index .env.example; echo "Exit-Code: $?"

Expected:

.gitignore:6:!.env.example  .env.example
Exit-Code: 0
Exit-Code: 1

Second: a file in an ignored folder can’t be brought back.

printf 'Hier liegen lokale Secret-Dateien.\n' > secrets/README.md
echo '!secrets/README.md' >> .gitignore
git check-ignore -v secrets/README.md
git restore .gitignore && rm secrets/README.md

Expected:

.gitignore:9:secrets/   secrets/README.md

Git doesn’t even enter secrets/, so the exception is never checked. If you want a README in the secrets folder, write secrets/* instead of secrets/ and after it !secrets/README.md.

Save your progress? Sign up for free

Drill 6: .dockerignore – same intent, different rules

Your project .dockerignore from Day 3 contains .env and .env.*. Now someone creates a service .env for go run:

printf '%s\n' NOTES_API_KEY=lab-api-key-456 > notes-api/.env
git check-ignore -q notes-api/.env && echo "Git: ignoriert"
rm -rf /tmp/notes-ctx
printf 'FROM scratch\nCOPY . /\n' \
  | docker build -q -f - -o type=local,dest=/tmp/notes-ctx . >/dev/null
find /tmp/notes-ctx -name '*.env*' -o -name secrets

Expected (abbreviated, may vary by version):

Git: ignoriert
/tmp/notes-ctx/secrets
/tmp/notes-ctx/notes-api/.env
/tmp/notes-ctx/lab.env
/tmp/notes-ctx/.env.example

The trick from Day 3: a FROM scratch with COPY . / copies exactly what arrives at the builder, and -o type=local writes it to /tmp/notes-ctx. Besides the service .env, lab.env and secrets/ are also in there. Why does the service .env end up in the context? In .gitignore, a pattern without / applies at any depth. In .dockerignore, every pattern applies from the root of the context; for all levels you need **/. The final project .dockerignore covers both and also excludes .env.example – the template isn’t needed in any image:

cat > .dockerignore <<'EOF'
# .dockerignore in the project folder – applies when the project folder is the build context.
# Patterns apply from the context root: for all levels you need **/.
# Secrets and local values (also .env.example: doesn't belong in the image)
**/.env*
**/*.env
**/secrets
**/*.pem
**/*.key
**/.npmrc
# Repository, build files, docs
.git
**/.gitignore
**/Dockerfile*
**/.dockerignore
**/*.md
compose.yaml
.hadolint.yaml
# Dependencies and artifacts the build creates itself
**/node_modules
**/dist
**/.venv
**/__pycache__
**/*.pyc
**/*.test
**/.DS_Store
EOF
rm -rf /tmp/notes-ctx
printf 'FROM scratch\nCOPY . /\n' \
  | docker build -q -f - -o type=local,dest=/tmp/notes-ctx . >/dev/null
find /tmp/notes-ctx -name '*.env*' -o -name secrets | wc -l
find /tmp/notes-ctx -type f | wc -l

Expected (abbreviated, may vary by version):

0
12

File counts and sizes will differ on your machine. The service .dockerignore files get the same secret patterns. Take them from the companion code and compare with your state from Day 6:

for d in notes-api notes-worker notes-web; do
  cp "$LAB/code/tag12/notes/$d/.dockerignore" "$d/"
done
grep -c -E '^\*\*/(\.env\*|\*\.env|\*\.pem|\*\.key)$' \
  notes-api/.dockerignore notes-worker/.dockerignore notes-web/.dockerignore

Expected:

notes-api/.dockerignore:4
notes-worker/.dockerignore:4
notes-web/.dockerignore:4
File .env in subfolders .env.example node_modules/
.gitignore .env is enough !.env.example: into the repo at any depth
.dockerignore needs **/.env exclude as well only with **/

Tip: A .gitignore can’t simply be copied as a .dockerignore. Docker ignores leading and trailing /; there, node_modules/ only means “node_modules in the root folder”.

Save your progress? Sign up for free

Drill 7: Compose reads .env – twice

The book’s first compose.yaml. It only does what you need for secrets:

cat > compose.yaml <<'EOF'
# compose.yaml – first version (Day 12): only as much Compose as secrets need.
# Compose reads the .env in the project folder for ${…} (interpolation);
# env_file: .env additionally puts its content into the container environment.
name: notes

services:
  notes-api:
    build: notes-api
    image: notes-api:tag12
    container_name: notes-api
    env_file: .env
    ports:
      - "127.0.0.1:8080:8080"

  notes-worker:
    build: notes-worker
    image: notes-worker:tag12
    container_name: notes-worker
    env_file: .env
    environment:
      NOTES_API_URL: http://notes-api:8080
      INTERVAL: ${WORKER_INTERVAL:-10}
    depends_on:
      - notes-api

  notes-web:
    build: notes-web
    image: notes-web:tag12
    container_name: notes-web
    env_file: .env
    environment:
      NOTES_API_URL: http://notes-api:8080
    ports:
      - "127.0.0.1:3000:3000"
    depends_on:
      - notes-api
EOF
docker compose config | grep -E 'NOTES_API_KEY|INTERVAL'

Expected (abbreviated, may vary by version):

      NOTES_API_KEY: lab-api-key-456
      NOTES_API_KEY: lab-api-key-456
      INTERVAL: "10"
      NOTES_API_KEY: lab-api-key-456

docker compose config shows the final model: ${WORKER_INTERVAL:-10} is resolved, and the content of every env_file appears as environment in plaintext. Handy for debugging, fatal in a CI log or a ticket. Without values it goes like this:

docker compose config --no-interpolate --no-env-resolution \
  | grep -E -A2 'env_file|INTERVAL' | head -6
docker compose config --no-interpolate --no-env-resolution | grep -c lab-api-key

Expected (abbreviated, may vary by version):

    env_file:
      - path: /Users/du/docker-lab/tag12/.env
        required: true
--
      INTERVAL: ${WORKER_INTERVAL:-10}
0

--no-env-resolution leaves env_file as a reference, --no-interpolate leaves the ${…} expressions. A third leak is --environment: it prints all variables that Compose knows for interpolation, from the shell and .env.

And docker run --env-file? Same file, different parser. A comment at the end of a line shows the difference:

printf '%s\n' 'NOTES_API_KEY=lab-api-key-456 # Lab-Wert' > lab.env
docker run --rm --env-file lab.env golang:1.27-alpine printenv NOTES_API_KEY
docker compose --env-file lab.env config --environment | grep '^NOTES_API_KEY'
rm lab.env

Expected (abbreviated, may vary by version):

lab-api-key-456 # Lab-Wert
NOTES_API_KEY=lab-api-key-456

For docker run --env-file, a # in the middle of the line is part of the value. Compose treats # after an unquoted value as a comment. So keep .env simple: one variable per line, comments only on their own lines.

Save your progress? Sign up for free

Drill 8: Who wins?

Two separate questions: where does the value for ${…} come from (interpolation), and which value ends up in the container?

worker='.services["notes-worker"].environment | {INTERVAL, WORKER_INTERVAL}'
api='.services["notes-api"].environment | {NOTES_API_KEY, WORKER_INTERVAL}'
docker compose config --format json | jq -c "$worker"
echo 'WORKER_INTERVAL=5' >> .env
docker compose config --format json | jq -c "$worker"
WORKER_INTERVAL=3 docker compose config --format json | jq -c "$worker"
NOTES_API_KEY=lab-api-key-123 docker compose config --format json | jq -c "$api"

Expected (abbreviated, may vary by version):

{"INTERVAL":"10","WORKER_INTERVAL":null}
{"INTERVAL":"5","WORKER_INTERVAL":"5"}
{"INTERVAL":"3","WORKER_INTERVAL":"5"}
{"NOTES_API_KEY":"lab-api-key-456","WORKER_INTERVAL":"5"}

What you’ve just seen:

  • Interpolation: shell before --env-file before .env before the default value from ${VAR:-…}. Line 3: INTERVAL follows the shell.
  • env_file: .env sends every line to every service that loads it – including WORKER_INTERVAL to notes-api. The .env has two roles.
  • A shell variable doesn’t change a value from env_file: WORKER_INTERVAL stays at 5 in line 3, and the old key from the shell doesn’t arrive in line 4. The shell only applies where compose.yaml asks via ${…}.
Rank Source for the container value
1 docker compose run -e
2 environment: or env_file: with an interpolated value (${…}, shell/.env)
3 environment: with a fixed value
4 env_file:
5 ENV in the image

The table follows the Compose docs (“Environment variables precedence”). Finally, remove the line again and start everything once:

grep -v '^WORKER_INTERVAL=' .env > .env.neu && mv .env.neu .env
WORKER_INTERVAL=2 docker compose up -d --build
curl -s -X POST localhost:3000/api/notes -H 'Content-Type: application/json' \
  -d '{"text":"Tag 12 über notes-web"}'
sleep 3; docker compose logs notes-worker | tail -1
docker compose down

Expected (abbreviated, may vary by version):

 ✔ Container notes-api     Started
 ✔ Container notes-worker  Started
 ✔ Container notes-web     Started
{"id":"2b7e…","text":"Tag 12 über notes-web"}
notes-worker  | summary: 1 notes, 4 words
 ✔ Container notes-web     Removed
 ✔ Container notes-worker  Removed
 ✔ Container notes-api     Removed
 ✔ Network notes_default   Removed

All three services have the key from env_file – and docker inspect shows it for each of them (Day 11, Drill 3). Day 14 replaces it with a secret file.

Save your progress? Sign up for free

Checkpoint

Git ignores the .env:

cd ~/docker-lab/tag12
git check-ignore -v .env

Expected:

.gitignore:4:.env   .env

The template .env.example stays visible:

git check-ignore --no-index .env.example; echo "Exit: $?"

Expected:

Exit: 1

No ignored file left in the index:

git ls-files --cached --ignored --exclude-standard

Expected: no output.

The key is rotated:

grep NOTES_API_KEY .env

Expected:

NOTES_API_KEY=lab-api-key-456

The .dockerignore applies at any depth:

grep -x '\*\*/.env\*' .dockerignore

Expected:

**/.env*

The safe config output contains no key:

docker compose config --no-interpolate --no-env-resolution | grep -c lab-api-key

Expected:

0

Challenge

Write a Git hook .git/hooks/pre-commit that aborts the commit if a staged file is named .env or .env.* (except .env.example) or contains a value matching the pattern lab-api-key-<digits>. Test it with git add -f .env, with a docs file that quotes a key, and with a harmless commit.

Hint: git diff --cached --name-only -z returns the staged files, git show ":<path>" their staged content – not the one in the working copy.

Solution

The file is also available at ~/docker-lab/code/tag12/pre-commit.

cat > .git/hooks/pre-commit <<'EOF'
#!/usr/bin/env bash
# pre-commit – aborts the commit if .env files or lab keys are staged.
# Install: cp pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit
set -euo pipefail
muster='lab-api-key-[0-9]+'
fail=0
while IFS= read -r -d '' f; do
  case "$(basename "$f")" in
    .env.example) ;;
    .env | .env.*)
      echo "✘ $f: .env-Dateien gehören nicht ins Repository"
      fail=1
      ;;
  esac
  if git show ":$f" | grep -qE -- "$muster"; then
    echo "✘ $f: enthält einen API-Key ($muster)"
    fail=1
  fi
done < <(git diff --cached --name-only -z --diff-filter=ACMR)
if [ "$fail" -ne 0 ]; then
  echo "Commit abgebrochen."
  exit 1
fi
EOF
chmod +x .git/hooks/pre-commit

Three tests:

git add -f .env && git commit -q -m "test: .env"; echo "Exit-Code: $?"
git reset -q .env
echo 'curl -H "X-API-Key: lab-api-key-456" localhost:8080/notes' > HOWTO.md
git add HOWTO.md && git commit -q -m "docs: Howto"; echo "Exit-Code: $?"
git reset -q HOWTO.md && rm HOWTO.md
git add compose.yaml .dockerignore notes-*/.dockerignore
git commit -q -m "build: compose.yaml, finale .dockerignore"; echo "Exit-Code: $?"

Expected:

✘ .env: .env-Dateien gehören nicht ins Repository
✘ .env: enthält einen API-Key (lab-api-key-[0-9]+)
Commit abgebrochen.
Exit-Code: 1
✘ HOWTO.md: enthält einen API-Key (lab-api-key-[0-9]+)
Commit abgebrochen.
Exit-Code: 1
Exit-Code: 0

--diff-filter=ACMR leaves out deleted files; otherwise git show would fail. The hook lives in .git/hooks and isn’t committed; everyone on the team has to install it themselves, and git commit --no-verify bypasses it. Clean up:

rm -rf /tmp/notes-ctx
docker ps -a --filter name=^notes- --format '{{.Names}}' | xargs -r docker rm -f
docker image ls --format '{{.Repository}}:{{.Tag}}' \
  | grep -E '^(notes-|localhost:5001/)' | xargs -r docker rmi
docker buildx prune --builder docker-lab --all --force

Save your progress? Sign up for free

Enterprise Note

  • Local hooks are a convenience layer. What’s binding is the platform’s push protection (GitHub secret scanning with push protection, GitLab secret push protection) plus a secret scan in the pipeline.
  • For hooks in a team there are ready-made scanners, such as gitleaks (brew install gitleaks, hook via the pre-commit framework). According to its README, the project is feature-complete and only receives security updates.
  • A key in the Git history is compromised, even in a private repository: rotate, then clean up with git filter-repo, coordinate the force push, collect clones and forks.
  • .env is a developer tool. In production, secrets come from a secret store; see “OpenBao secrets hands-on”.
  • docker compose config belongs in a CI log only with --quiet or with --no-interpolate --no-env-resolution.