개발이 취미인 사람

[Git] - .gitignore 설정 방법 본문

컴퓨터공학/Git

[Git] - .gitignore 설정 방법

RyanSin 2025. 12. 18. 20:00
반응형

개요

안녕하세요. 이번 시간에는 .gitignore 설정 방법에 대해 알아보겠습니다. 프로젝트를 진행하다 보면 Git으로 관리하지 않아야 할 파일들이 있습니다. 예를 들어 빌드 결과물, 환경 설정 파일, 의존성 폴더 등이 있죠. 이런 파일들을 무시하도록 설정하는 방법을 알아보겠습니다. 혹시 이전 시간에 내용을 학습하고 오시지 못 하신 분들은 학습하고 오시는 걸 추천드리겠습니다.

 

Git 기본 명령어 (init, add, commit, status, log)

 

- .gitignore란?

.gitignore는 Git이 추적하지 않을 파일이나 디렉토리를 지정하는 설정 파일입니다. 프로젝트 루트 디렉토리에 .gitignore 파일을 생성하고, 무시할 파일 패턴을 작성하면 됩니다.

왜 필요한가?

Git으로 관리하면 안 되는 파일들이 있습니다.

종류 예시 이유

의존성 폴더 node_modules/, venv/ 용량이 크고 재설치 가능
빌드 결과물 dist/, build/, *.class 소스로부터 생성 가능
환경 설정 .env, *.local 민감한 정보 포함
IDE 설정 .idea/, .vscode/ 개인 환경 설정
시스템 파일 .DS_Store, Thumbs.db OS 자동 생성 파일
로그 파일 *.log, logs/ 런타임 생성 파일

- .gitignore 기본 문법

파일 생성

# 프로젝트 루트에서 .gitignore 파일 생성
touch .gitignore

# 또는 에디터로 직접 생성
code .gitignore

기본 패턴

# 특정 파일 무시
secret.txt

# 특정 확장자 무시
*.log
*.tmp

# 특정 디렉토리 무시 (끝에 / 붙이기)
node_modules/
dist/
build/

# 루트 디렉토리의 특정 파일만 무시 (맨 앞에 /)
/config.local.js

# 특정 디렉토리 내의 특정 파일
logs/*.log

# 주석
# 이것은 주석입니다

패턴 규칙 정리

패턴 설명 예시

file.txt 모든 위치의 file.txt src/file.txt, lib/file.txt
/file.txt 루트의 file.txt만 ./file.txt
dir/ dir 디렉토리 전체 dir/, src/dir/
*.log 모든 .log 파일 error.log, debug.log
*.log 특정 폴더 내 .log logs/error.log
!important.log important.log는 제외 (무시 안함)

- 와일드카드 패턴

별표 (*)

0개 이상의 문자와 매칭됩니다.

# 모든 .log 파일
*.log

# 모든 .txt 파일
*.txt

# test로 시작하는 모든 파일
test*

물음표 (?)

정확히 1개의 문자와 매칭됩니다.

# file1.txt, file2.txt 등 (file?.txt)
file?.txt

# 매칭: file1.txt, fileA.txt
# 비매칭: file10.txt, file.txt

이중 별표 (**)

디렉토리를 재귀적으로 매칭합니다.

# 모든 하위 디렉토리의 .log 파일
**/*.log

# logs 디렉토리 아래 모든 파일
logs/**

# 모든 build 디렉토리
**/build/

대괄호 ([])

문자 집합 중 하나와 매칭됩니다.

# file1.txt, file2.txt, file3.txt
file[123].txt

# file1.txt ~ file9.txt
file[0-9].txt

# filea.txt ~ filez.txt
file[a-z].txt

- 부정 패턴 (!)

무시 패턴에서 특정 파일을 제외합니다.

# 모든 .log 파일 무시
*.log

# 하지만 important.log는 추적
!important.log
# build 폴더 무시
build/

# 하지만 build/keep.txt는 유지
!build/keep.txt

⚠️ 주의: 부정 패턴은 이미 상위 디렉토리가 무시되면 동작하지 않습니다.

# 이렇게 하면 안됨! (동작 안함)
build/
!build/keep.txt

# 이렇게 해야 함
build/*
!build/keep.txt

- 언어/프레임워크별 .gitignore

Node.js / JavaScript

# Dependencies
node_modules/

# Build
dist/
build/

# Environment
.env
.env.local
.env.*.local

# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# IDE
.idea/
.vscode/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db

# Test
coverage/

Java / Spring Boot

# Compiled
*.class
*.jar
*.war

# Build
target/
build/
out/

# IDE
.idea/
*.iml
.project
.classpath
.settings/

# Gradle
.gradle/
gradle-app.setting

# Maven
pom.xml.tag
pom.xml.next

# Environment
application-local.yml
application-local.properties

# Logs
*.log
logs/

Python

# Byte-compiled
__pycache__/
*.py[cod]
*$py.class

# Virtual Environment
venv/
.venv/
ENV/

# Distribution
dist/
build/
*.egg-info/

# IDE
.idea/
.vscode/
*.swp

# Environment
.env
.env.local

# Jupyter
.ipynb_checkpoints/

# Test
.pytest_cache/
htmlcov/
.coverage

React / Vue

# Dependencies
node_modules/

# Build
dist/
build/
.next/
.nuxt/

# Environment
.env
.env.local
.env.*.local

# Logs
npm-debug.log*
yarn-debug.log*

# IDE
.idea/
.vscode/

# Test
coverage/

# Misc
.DS_Store
*.local

- 전역 .gitignore 설정

모든 프로젝트에 공통으로 적용할 .gitignore를 설정할 수 있습니다.

# 전역 gitignore 파일 생성
touch ~/.gitignore_global

# Git에 전역 gitignore 등록
git config --global core.excludesfile ~/.gitignore_global

~/.gitignore_global 예시:

# OS 파일
.DS_Store
.DS_Store?
._*
Thumbs.db

# IDE
.idea/
.vscode/
*.swp
*.swo
*~

# 로그
*.log

- 이미 추적 중인 파일 무시하기

.gitignore는 아직 추적되지 않은 파일에만 적용됩니다. 이미 Git이 추적 중인 파일은 .gitignore에 추가해도 계속 추적됩니다.

해결 방법

# 1. 캐시에서 파일 제거 (파일은 유지)
git rm --cached 파일명

# 2. 디렉토리인 경우 -r 옵션 추가
git rm --cached -r 디렉토리명/

# 3. 커밋
git commit -m "chore: .gitignore 적용"

실습 예시

# node_modules가 이미 커밋된 경우
git rm --cached -r node_modules/

# .env 파일이 이미 커밋된 경우
git rm --cached .env

# 변경사항 커밋
git commit -m "chore: 불필요한 파일 추적 제거"

⚠️ 주의: git rm --cached는 Git 추적만 제거합니다. 실제 파일은 삭제되지 않습니다. 하지만 다른 팀원이 pull 받으면 해당 파일이 삭제될 수 있으니 주의하세요!

- .gitignore 템플릿 활용

gitignore.io 사용

gitignore.io 사이트에서 프로젝트에 맞는 .gitignore를 자동 생성할 수 있습니다.

# 커맨드라인에서 직접 생성
# Node.js + macOS + VS Code
curl -sL https://www.toptal.com/developers/gitignore/api/node,macos,visualstudiocode

GitHub 템플릿

GitHub에서 저장소 생성 시 .gitignore 템플릿을 선택할 수 있습니다.

또는 github/gitignore 저장소에서 다양한 템플릿을 확인할 수 있습니다.

- .gitignore 디버깅

특정 파일이 왜 무시되는지 확인하는 방법입니다.

# 특정 파일이 무시되는 이유 확인
git check-ignore -v 파일명

# 예시
git check-ignore -v node_modules/

# 출력
.gitignore:3:node_modules/    node_modules/
# .gitignore 파일의 3번째 줄 때문에 무시됨
# 무시되는 모든 파일 목록
git status --ignored

- 실습: 프로젝트 .gitignore 설정

Node.js 프로젝트를 예시로 전체 실습을 진행합니다.

# 1. 프로젝트 생성
mkdir my-node-project
cd my-node-project
git init
npm init -y

# 2. 의존성 설치
npm install express

# 3. 파일 생성
echo "DB_PASSWORD=secret123" > .env
echo "console.log('Hello');" > index.js

# 4. 현재 상태 확인 (node_modules가 보임)
git status

# 5. .gitignore 생성
cat << 'EOF' > .gitignore
# Dependencies
node_modules/

# Environment
.env
.env.local

# Logs
*.log
npm-debug.log*

# OS
.DS_Store
Thumbs.db

# IDE
.idea/
.vscode/
EOF

# 6. 다시 상태 확인 (node_modules, .env가 안보임)
git status

# 7. 커밋
git add .
git commit -m "init: 프로젝트 초기 설정"

마무리

이번 시간에는 .gitignore 설정 방법에 대해 알아봤습니다. .gitignore를 잘 설정하면 불필요한 파일이 저장소에 올라가는 것을 방지하고, 민감한 정보를 보호할 수 있습니다. 프로젝트 시작 시 가장 먼저 .gitignore를 설정하는 습관을 들이시길 추천드립니다.

다음 시간에는 브랜치(Branch) 개념과 생성/삭제에 대해 알아보겠습니다.


참고 자료