When working with Git, it’s important to avoid accidentally tracking files that shouldn’t be in your repository — like build artifacts, configuration secrets, or dependencies. That’s where a .gitignore
file comes in.
In this guide, you’ll learn how to create and use a .gitignore
file to keep your Git repository clean and secure.
📄 What is a .gitignore
File?
A .gitignore
file tells Git which files or directories to ignore — meaning they won’t be tracked or committed to your repository.
Typical examples of ignored files include:
node_modules/
(Node.js dependencies)*.log
(log files)__pycache__/
(Python bytecode).env
(environment variables)
🛠 How to Add a .gitignore
File
✅ Option 1: Create .gitignore
Manually
- Navigate to your project directory.
- Create a file named
.gitignore
:
touch .gitignore
- Open it in a text editor and add the patterns you want to ignore:
# Node.js dependencies
node_modules/
# Logs
*.log
# Environment files
.env
- Save the file and stage it:
git add .gitignore
git commit -m "Add .gitignore file"
git push origin main
✅ Option 2: Use a Template Generator (e.g., GitHub)
When creating a new repository on GitHub, you can choose a .gitignore
template for your tech stack (Node, Python, Java, etc.).
Just select the language/environment under “Add .gitignore” during repo creation.
You can also find ready-to-use templates at:
👉 https://github.com/github/gitignore
🔄 Ignore Already-Tracked Files
If you’ve already committed files that should be ignored, .gitignore
alone won’t remove them. You’ll need to untrack them:
git rm -r --cached node_modules/
git commit -m "Remove ignored files from repo"
Then push the change:
git push origin main
✨ Example: Sample .gitignore
for Node.js
# dependencies
node_modules/
# production
dist/
build/
# misc
.env
*.log
.DS_Store
✅ Summary
Task | Command |
---|---|
Create .gitignore | touch .gitignore |
Add rules | Edit and list files/directories to ignore |
Stage and commit | git add .gitignore && git commit -m "Add .gitignore" |
Remove tracked ignored files | git rm --cached <file> |
🚀 Conclusion
A well-configured .gitignore
file is essential for any Git project. It helps maintain a clean codebase, protects sensitive information, and avoids committing unnecessary files. Whether you’re working solo or on a team, investing a few minutes to set this up pays off in the long run.