Key Recommendations on the Usage of .gitignore file and Example
You can create the .gitignore file before or after running git init, but the best practice to create first. This ensures that when you initialize Git, it immediately ignores unnecessary files. Then run git init to initialize the repository with the correct ignored files in place.
echo "target/" >> .gitignore # Step 1: Create .gitignore with ignored files
Doing it Other Way
If you run git init first and then create .gitignore, any ignored files already added to Git won't be removed automatically. You'll need to manually remove them:
git rm -r --cached target/ # Removes ignored files from tracking
git commit -m "Updated .gitignore" # Commit changes
Example for Maven + Spring Boot
Create a .gitignore file in your project's root directory and add these entries to exclude unnecessary files:
# Ignore target folder (Maven compiled files)
target/
# Ignore build folder (Gradle compiled files)
build/
# Ignore IntelliJ IDEA and VSCode settings
.idea/
.vscode/
# Ignore logs and temp files
logs/
*.log
*.tmp
# Ignore OS-specific files
.DS_Store
Thumbs.db
# Ignore dependencies (use Maven/Gradle to fetch them)
*.jar
*.war
*.class
# Ignore environment variables and secrets
.env
application.properties
application.yml
If your application.properties contains database credentials, never push it to GitHub. You can use environmental variables instead.