Chapter 6 · Lesson 9 of 10
Git for deployers

Gitignore and keeping secrets out of Git

A .gitignore file lists patterns Git should not track, and secrets such as .env files belong there, because anything committed stays in history even after you delete it.

By the end you will

Ignore files with .gitignore, untrack files already committed, keep config in .env.example, and respond correctly when a secret leaks.

Time
15 min
Level
Beginner
Check
4 questions
You need
  • A Git repository with a few files

Put files that must not be shared into .gitignore, and keep real secrets in an .env file that is ignored, with a .env.example committed beside it. If a secret does get committed, rotate it first: change the password or revoke the token, because deleting it from a later commit leaves it in history. Cleaning history is a second, optional step.

How it works#

Git tracks every file you git add. A .gitignore file in the repository root lists patterns of files Git should leave alone, and each line is one pattern. Git skips matching untracked files, so they stay out of git status and out of git add .. It does nothing for a file that was already committed, which is the most common surprise.

Why care? A repository is a permanent record. Every commit is stored in full, and clones copy all of it. A password committed once is readable by anyone with the repository, in any old commit, until you rotate it. Secrets and build output both belong outside Git. For how apps read configuration instead, see environment variables and secrets.

Step 1: Write a .gitignore#

Create .gitignore at the top of the repository and commit it, so everyone shares the rules:

output
# secrets and local config
.env
*.pem
*.key

# dependencies and build output
node_modules/
dist/
build/

# logs and editor files
*.log
.DS_Store
.vscode/

Pattern rules:

  • * matches any characters within one folder level, **/ matches across folders.
  • A trailing / matches directories only (dist/).
  • A leading / anchors to the repository root (/config.local).
  • ! re-includes a file that an earlier pattern excluded (!.env.example).
  • # starts a comment.

You can also keep personal ignores for your own machine in .git/info/exclude, or a global file set with git config --global core.excludesFile ~/.gitignore_global.

Step 2: Check what a rule does#

bash
git check-ignore -v .env

The output is the file, the line number and the pattern that matched, for example .gitignore:2:.env .env. No output means the path is not ignored. List what Git currently ignores with git status --ignored.

Step 3: Stop tracking a file you already committed#

Adding a pattern is not enough for tracked files. Remove them from the index only:

bash
git rm --cached .env
git commit -m "stop tracking .env"

--cached removes the file from Git but leaves it on disk. For a folder, add -r: git rm -r --cached node_modules. Be careful: after a teammate pulls this commit, Git deletes their copy of the file in their working tree, so back up local config first. Without --cached, the file is deleted from disk too.

Step 4: Use .env and .env.example#

Keep real values in .env, ignored. Commit a template with the names and harmless placeholders:

output
# .env.example
DATABASE_URL=postgres://app:change-me@localhost:5432/app
SESSION_SECRET=change-me
SMTP_HOST=smtp.example.com

New developers run cp .env.example .env and fill in real values. On servers, supply the real file through your deploy tooling or the host’s secret store, not through Git. Replace every change-me with a long random value, such as the output of openssl rand -hex 32. See the blog post on managing secrets for self-hosted Docker for container setups.

If a secret was committed#

Work in this order:

  1. Rotate it now. Change the database password, revoke the API token, delete and recreate the SSH key. This is the step that actually protects you. A leaked secret is compromised from the moment it is pushed.
  2. Remove it from the code. Delete it, use an environment variable, add the file to .gitignore, and commit.
  3. Decide about history. If the repository is private and small, the rotation may be enough. For a public repository, assume the old value is already scraped. Tools such as git filter-repo can rewrite history to remove a file or string, but they change every later commit hash, require a force push, and force every collaborator to re-clone. Cached copies and forks may still hold the old data. Read the tool’s documentation before you run it, and make a backup first.
  4. Check logs and access. Look for use of the leaked credential between the commit and the rotation.

Pushing the removal on top of a leaked commit changes nothing for people who already have it.

The same rule applies to a public key versus a private key: the private one never goes into a repository, as covered in SSH keys and deploy keys.

Check it worked#

bash
git status --short
git ls-files | grep -E '^\.env$'

The first should not list ignored files. The second prints nothing if .env is not tracked. Also search history for a known string:

bash
git log --all -S 'change-me' --oneline

-S finds commits that added or removed that text. Use it with a snippet of a real secret locally to see whether it exists in history. Do not paste a real secret into a shared terminal log.

Edge cases and gotchas#

  • Ignore rules do not rewrite history. They only prevent future adds.
  • Negation needs a visible parent. ! cannot re-include a file if its parent folder is ignored.
  • Ignored does not mean private. A file can still end up in a Docker image if the build copies the folder. Use a .dockerignore too.
  • Line endings in .gitignore. Trailing spaces count as part of a pattern, which makes a rule silently fail.
  • Nested .gitignore files. A subfolder can have its own file with its own rules. Check all of them when something is oddly tracked.
  • Public repositories are scanned. Bots look for keys within minutes. Treat any leak there as immediate.

Troubleshooting#

SymptomLikely causeFix
A file is still listed in git status after adding it to .gitignoreIt is already trackedgit rm --cached file, commit
fatal: pathspec '.env' did not match any filesThe file is not trackedIt is already untracked, check git check-ignore -v .env
The following paths are ignored by one of your .gitignore files:git add on an ignored fileRemove the rule, or force once with git add -f if you really mean it
error: the following file has staged content different from both the file and the HEADgit rm --cached on a modified staged fileUse git rm --cached -f file
fatal: not removing 'dir' recursively without -rA folder was givenAdd -r
remote: error: GH013: Repository rule violations found or a secret scanning blockThe host detected a secret in the pushRemove it, rotate it, and push again
A pattern like *.env ignores .env.example tooWrong patternAdd !.env.example after it
warning: LF will be replaced by CRLFLine ending settingsInformational, set core.autocrlf or .gitattributes

Quick reference#

bash
cat .gitignore
git check-ignore -v path
git status --ignored
git rm --cached file             # untrack, keep on disk
git rm -r --cached dir
git add -f file                  # add an ignored file anyway
git log --all -S 'text' --oneline
cp .env.example .env

Next#

Put it all together in a Git workflow that triggers a deploy.

Check what you learned4 questions
1A secret was pushed to a repository. What is the first action?
2How do you stop tracking a file that is already committed but keep it on disk?
3What does the pattern /build/ match?
4Which command tells you which rule is ignoring a file?

Frequently asked questions

What does .gitignore do?

It tells Git which untracked files and folders to skip, so they do not show in git status and are not added by git add. It does not affect files that are already tracked.

Why is my file still tracked after adding it to .gitignore?

.gitignore only applies to untracked files. Stop tracking it with git rm --cached file, commit, and from then on it is ignored. The file stays on disk.

I committed a password to Git. What do I do?

Rotate the password right away, because anyone who saw the repository may have it. Then remove it from the code and, if needed, from history. Removing it from history alone is not enough.

Should I commit my .env file?

No. Commit a .env.example with the variable names and safe placeholder values, and keep the real .env out of Git.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios