Programmer/AI

Claude Code 컨테이너 격리와 병렬 개발: devcontainer & git worktree

MoreLean 2026. 1. 21. 00:54
반응형

컨테이너 격리도 중요해요. 특히 프로젝트 여러 개 동시에 진행할 때요.

Docker나 devcontainer 쓰면 환경이 완전히 분리돼요. A 프로젝트 Node 버전이랑 B 프로젝트 Node 버전 충돌 걱정 없어지죠.

Claude Code도 devcontainer 지원해요. .devcontainer 폴더 만들고 설정 파일 넣으면 자동으로 컨테이너 안에서 작업해요. 환경 꼬일 일이 없어요.


TL;DR

컨테이너 격리 (devcontainer)

  • 프로젝트별 완전한 환경 분리
  • Node/Python 버전 충돌 없음
  • YOLO 모드를 안전하게 사용 가능
  • Anthropic 공식 레퍼런스 제공

병렬 개발 (git worktree)

  • 여러 Claude 인스턴스 동시 실행
  • 같은 레포에서 독립적 작업
  • 디스크 공간 효율적 (전체 복사 X)
  • 공식 베스트 프랙티스로 권장

Part 1: devcontainer로 환경 격리

왜 컨테이너 격리가 필요한가?

"Use devcontainers to isolate different client projects, ensuring code and credentials never mix between environments." — Claude Code Docs

흔한 문제들:

  • A 프로젝트: Node 18, B 프로젝트: Node 20 → 충돌
  • 전역 패키지가 서로 영향
  • "내 컴퓨터에서는 되는데..." 문제
  • YOLO 모드 사용 시 보안 우려

devcontainer 해결:

  • 프로젝트마다 완전히 격리된 환경
  • 호스트 시스템에 영향 없음
  • 팀원 모두 동일한 환경
  • 컨테이너 안에서 YOLO 모드 안전하게 사용

Anthropic 공식 devcontainer

Anthropic이 공식 레퍼런스 devcontainer를 제공해요:

"The reference devcontainer setup and associated Dockerfile offer a preconfigured development container that you can use as is, or customize for your needs." — Claude Code Docs

구성 파일:

.devcontainer/
├── devcontainer.json   # 컨테이너 설정, 확장, 볼륨 마운트
├── Dockerfile          # 컨테이너 이미지 정의
└── init-firewall.sh    # 네트워크 보안 규칙

빠른 시작 (4단계)

# 1. VS Code와 Dev Containers 확장 설치

# 2. Anthropic 공식 레퍼런스 클론
git clone https://github.com/anthropics/claude-code.git
cd claude-code

# 3. VS Code로 열기
code .

# 4. "Reopen in Container" 클릭 (또는 Cmd+Shift+P → "Remote-Containers: Reopen in Container")

기본 devcontainer.json 예시

{
  "name": "Claude Code Dev",
  "image": "mcr.microsoft.com/devcontainers/javascript-node:20",
  
  "features": {
    "ghcr.io/devcontainers/features/git:1": {}
  },
  
  "customizations": {
    "vscode": {
      "extensions": [
        "dbaeumer.vscode-eslint",
        "esbenp.prettier-vscode"
      ]
    }
  },
  
  "postCreateCommand": "npm install -g @anthropic-ai/claude-code",
  
  "remoteUser": "node",
  
  "containerEnv": {
    "CLAUDE_CONFIG_DIR": "/home/node/.claude"
  },
  
  "mounts": [
    "source=claude-config,target=/home/node/.claude,type=volume"
  ]
}

보안 기능

Anthropic devcontainer의 다층 보안:

"The container implements a multi-layered security approach with its firewall configuration." — Claude Code Docs

보안 레이어 설명

정밀 접근 제어 화이트리스트 도메인만 허용 (npm, GitHub, Claude API)
Default-deny 기타 모든 외부 네트워크 차단
시작 검증 컨테이너 초기화 시 방화벽 규칙 검증
격리 메인 시스템과 완전 분리

YOLO 모드 안전하게 사용하기

devcontainer 안에서는 YOLO 모드를 상대적으로 안전하게 사용할 수 있어요:

# 컨테이너 안에서
claude --dangerously-skip-permissions

"The container's enhanced security measures (isolation and firewall rules) allow you to run claude --dangerously-skip-permissions to bypass permission prompts for unattended operation." — Claude Code Docs

⚠️ 주의:

"devcontainers don't prevent a malicious project from exfiltrating anything accessible in the devcontainer including Claude Code credentials. We recommend only using devcontainers when developing with trusted repositories."

프로젝트별 환경 설정

Node.js 프로젝트:

{
  "name": "Node 20 Project",
  "image": "mcr.microsoft.com/devcontainers/javascript-node:20",
  "postCreateCommand": "npm install && npm install -g @anthropic-ai/claude-code"
}

Python 프로젝트:

{
  "name": "Python 3.12 Project", 
  "image": "mcr.microsoft.com/devcontainers/python:3.12",
  "postCreateCommand": "pip install -r requirements.txt && npm install -g @anthropic-ai/claude-code"
}

멀티 서비스 (Docker Compose):

# docker-compose.yml
version: '3.8'
services:
  app:
    build:
      context: ..
      dockerfile: .devcontainer/Dockerfile
    volumes:
      - ../..:/workspaces:cached
      - node-modules:/workspaces/project/node_modules
    depends_on:
      - db
    environment:
      - DATABASE_URL=postgresql://postgres:postgres@db:5432/mydb
      
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: mydb
    volumes:
      - postgres-data:/var/lib/postgresql/data

volumes:
  node-modules:
  postgres-data:

Claude 설정 영속화

컨테이너를 재빌드해도 Claude 인증이 유지되도록:

{
  "mounts": [
    "source=claude-code-config,target=/home/node/.claude,type=volume"
  ],
  "containerEnv": {
    "CLAUDE_CONFIG_DIR": "/home/node/.claude"
  }
}

Part 2: git worktree로 병렬 개발

왜 git worktree인가?

"Using git worktrees enables you to run multiple Claude sessions simultaneously on different parts of your project, each focused on its own independent task." — Anthropic Best Practices

문제: 여러 Claude 인스턴스를 같은 디렉토리에서 실행하면 서로 충돌해요. 파일을 동시에 수정하면서 엉망이 됩니다.

해결: git worktree로 격리된 작업 공간을 만들어 각 Claude가 독립적으로 작업하게 해요.

git worktree 기본 개념

# 일반적인 방식: 전체 레포 복사 (비효율적)
/projects/
├── my-project/           # 원본
├── my-project-copy-1/    # 전체 복사 (.git 포함)
└── my-project-copy-2/    # 전체 복사 (.git 포함)

# git worktree 방식: 작업 파일만 분리 (효율적)
/projects/
├── my-project/           # 메인 (.git 여기에만)
├── feature-auth/         # worktree (링크만)
└── feature-api/          # worktree (링크만)

장점:

  • 디스크 공간 효율적 (node_modules 복사 X)
  • 모든 worktree가 동기화 (fetch가 전체에 적용)
  • 같은 브랜치 중복 체크아웃 방지

git worktree와 branch의 관계

핵심 원칙: 1 worktree = 1 branch (1:1 관계)

┌─────────────────────────────────────────────────────────────┐
│                    .git/ (공유)                              │
│  ┌──────────────┬──────────────┬──────────────┐            │
│  │   objects/   │    refs/     │   config     │            │
│  │  (커밋 히스토리) │  (브랜치 정보)  │   (설정)      │            │
│  └──────────────┴──────────────┴──────────────┘            │
└─────────────────────────────────────────────────────────────┘
         │                │                │
         ▼                ▼                ▼
┌─────────────┐  ┌─────────────┐  ┌─────────────┐
│ my-project/ │  │ feature-a/  │  │ hotfix/     │
│ (main)      │  │ (feat/a)    │  │ (fix/bug)   │
│             │  │             │  │             │
│ Working     │  │ Working     │  │ Working     │
│ Directory   │  │ Directory   │  │ Directory   │
└─────────────┘  └─────────────┘  └─────────────┘
   메인 worktree      worktree 1       worktree 2

공유되는 것:

  • .git/ 디렉토리 (히스토리, 설정, refs)
  • git fetch 결과 (한 곳에서 fetch하면 전체 적용)
  • remote 설정
  • hooks

공유되지 않는 것:

  • 작업 파일들 (각자 독립)
  • node_modules/, venv/ 등 (각 worktree에서 별도 설치 필요)
  • .env 파일 (복사 필요)
  • 스테이징 영역 (각자 독립적인 git add)

중요한 제약:

# ❌ 같은 브랜치를 두 worktree에서 체크아웃 불가!
git worktree add ../another main
# fatal: 'main' is already checked out at '/projects/my-project'

# ✅ 반드시 다른 브랜치여야 함
git worktree add ../feature-a -b feat/a

기본 사용법

# 1. 새 worktree 생성
git worktree add ../feature-auth -b feat/auth

# 2. 다른 터미널에서 해당 worktree로 이동
cd ../feature-auth

# 3. Claude Code 실행
claude

# 4. 작업 완료 후 worktree 제거
cd ../my-project
git worktree remove ../feature-auth

Part 2.5: 실무 Flow와 Best Practices

디렉토리 구조 Best Practice

권장 구조:

/projects/
├── my-project/              # 메인 worktree (main 브랜치)
│   ├── .git/                # 실제 Git 데이터 (여기만!)
│   ├── src/
│   ├── CLAUDE.md
│   └── ...
│
└── worktrees/               # worktree 전용 폴더 (프로젝트 밖)
    ├── feature/
    │   ├── user-auth/       # feat/user-auth 브랜치
    │   └── payment-api/     # feat/payment-api 브랜치
    ├── bugfix/
    │   └── login-error/     # fix/login-error 브랜치
    └── review/
        └── pr-123/          # PR 리뷰용

왜 프로젝트 밖에 둘까?

  • 메인 프로젝트가 깔끔하게 유지됨
  • Git이 worktree를 서브디렉토리로 착각하지 않음
  • IDE가 혼란스러워하지 않음

실무 시나리오별 Flow

시나리오 1: 긴급 핫픽스 (가장 흔함)

상황: feature 개발 중인데 프로덕션 버그 발생

# 현재: my-project/에서 feat/new-dashboard 작업 중

# 1. 핫픽스용 worktree 생성 (main 기반)
git worktree add ../worktrees/hotfix/payment-bug -b fix/payment-bug origin/main

# 2. 핫픽스 worktree로 이동
cd ../worktrees/hotfix/payment-bug

# 3. 의존성 설치 & 환경 설정
npm install
cp ../../my-project/.env .env

# 4. Claude로 버그 수정
claude
# "Fix the payment timeout issue in checkout flow"

# 5. 커밋 & 푸시
git add .
git commit -m "fix: payment timeout issue in checkout"
git push origin fix/payment-bug

# 6. PR 생성 (Claude가 gh CLI로 가능)
gh pr create --base main --title "Fix payment timeout"

# 7. 머지 후 정리
cd ../../../my-project
git worktree remove ../worktrees/hotfix/payment-bug
git branch -d fix/payment-bug

# 8. 원래 작업으로 복귀 (컨텍스트 그대로!)
claude --resume

Flow 다이어그램:

main ─────────────────●────────────────────────────────●─────
                      │                                ↑
                      │ git worktree add               │ merge
                      ▼                                │
fix/payment-bug ──────●────────●───────────────────────┘
                      │        │
                   worktree  commit
                   생성      & push

시나리오 2: 병렬 기능 개발

상황: 독립적인 2개 기능을 동시에 개발

# 1. 기능 A worktree
git worktree add ../worktrees/feature/user-profile -b feat/user-profile origin/develop
cd ../worktrees/feature/user-profile
npm install && cp ../../my-project/.env .env

# 2. 기능 B worktree (다른 터미널)
git worktree add ../worktrees/feature/notification -b feat/notification origin/develop
cd ../worktrees/feature/notification
npm install && cp ../../my-project/.env .env

# 3. 각 터미널에서 Claude 실행
# 터미널 1:
claude
# "Implement user profile edit functionality"

# 터미널 2:
claude
# "Implement push notification system"

# 4. 각자 완료되면 PR 생성
# 5. develop에 순차적으로 머지

Flow 다이어그램:

develop ────●─────────────────────────────●────────●─────
            │                             ↑        ↑
            ├─────────────────────────────┘        │
            │         feat/user-profile            │
            │                                      │
            └──────────────────────────────────────┘
                      feat/notification

시나리오 3: PR 리뷰 중 다른 작업

상황: 내 PR이 리뷰 중인데 다른 작업 시작해야 함

# 현재: feat/dashboard PR이 리뷰 중
# my-project/는 feat/dashboard 브랜치 상태

# 1. 새 작업용 worktree 생성
git worktree add ../worktrees/feature/analytics -b feat/analytics origin/develop

# 2. 새 작업 시작
cd ../worktrees/feature/analytics
claude
# 새 기능 개발...

# 3. 리뷰 코멘트 오면 원래 worktree로 돌아가기
cd ../my-project  # 여전히 feat/dashboard 상태!
claude --resume   # 컨텍스트 유지!
# 리뷰 반영...

# 4. 왔다갔다 가능 (컨텍스트 손실 없음!)

시나리오 4: 경쟁적 구현 (A/B 테스트)

상황: 같은 기능을 다른 방식으로 구현해서 비교

# 검색 기능을 3가지 방식으로 동시 구현
git worktree add ../worktrees/feature/search-elastic -b feat/search-elastic
git worktree add ../worktrees/feature/search-postgres -b feat/search-postgres
git worktree add ../worktrees/feature/search-algolia -b feat/search-algolia

# 각 worktree에서 Claude에게 다른 지시
# Elastic: "Implement search using Elasticsearch"
# Postgres: "Implement search using PostgreSQL full-text search"
# Algolia: "Implement search using Algolia API"

# 결과 비교 후 최적의 구현 선택
npm run benchmark  # 각 worktree에서 성능 테스트

Merge 전략

순차적 머지 (권장)

# 1. develop 최신화
cd my-project
git checkout develop
git pull origin develop

# 2. 기능 A 머지
git merge feat/user-profile
git push origin develop

# 3. 기능 B를 최신 develop에 리베이스 후 머지
cd ../worktrees/feature/notification
git fetch origin
git rebase origin/develop
# 충돌 해결 (필요시)
git push origin feat/notification --force-with-lease

cd ../my-project
git pull origin develop
git merge feat/notification
git push origin develop

tasks.md로 작업 추적

<!-- tasks.md (메인 worktree에 위치) -->
# 현재 진행 중인 작업

## Active Worktrees

| Worktree | Branch | 담당 | 상태 | 예상 완료 |
|----------|--------|------|------|----------|
| feature/user-profile | feat/user-profile | Claude-1 | 🟡 진행중 | 1/22 |
| feature/notification | feat/notification | Claude-2 | 🟢 PR 리뷰 중 | 1/21 |
| hotfix/payment | fix/payment-bug | Claude-3 | ✅ 머지됨 | 1/20 |

## Merge Order
1. ✅ fix/payment-bug → main (긴급)
2. 🔄 feat/notification → develop
3. ⏳ feat/user-profile → develop (notification 머지 후)

## Dependencies
- feat/user-profile은 feat/notification 완료 후 시작 가능한 부분 있음
- 공통 컴포넌트는 develop에서 먼저 작업

자동화 스크립트

worktree 생성 스크립트:

#!/bin/bash
# save as: scripts/new-worktree.sh

TYPE=$1  # feature, bugfix, hotfix, review
NAME=$2  # 작업 이름
BASE=${3:-origin/develop}  # 기본 브랜치

if [ -z "$TYPE" ] || [ -z "$NAME" ]; then
    echo "Usage: ./new-worktree.sh <type> <name> [base-branch]"
    echo "Example: ./new-worktree.sh feature user-auth"
    echo "         ./new-worktree.sh hotfix payment-bug origin/main"
    exit 1
fi

BRANCH="$TYPE/$NAME"
DIR="../worktrees/$TYPE/$NAME"

# 디렉토리 생성
mkdir -p "../worktrees/$TYPE"

# 최신 정보 fetch
git fetch origin

# worktree 생성
echo "🚧 Creating worktree: $DIR (branch: $BRANCH)"
git worktree add "$DIR" -b "$BRANCH" "$BASE"

if [ $? -eq 0 ]; then
    echo "✅ Worktree created!"
    echo ""
    echo "Next steps:"
    echo "  cd $DIR"
    echo "  npm install  # or your package manager"
    echo "  cp ../../my-project/.env .env  # if needed"
    echo "  claude"
else
    echo "❌ Failed to create worktree"
    exit 1
fi

정리 스크립트:

#!/bin/bash
# save as: scripts/cleanup-worktrees.sh

echo "🧹 Cleaning up merged worktrees..."

git worktree list | grep -v "$(git rev-parse --show-toplevel)" | while read -r line; do
    worktree_path=$(echo "$line" | awk '{print $1}')
    branch=$(echo "$line" | awk '{print $3}' | tr -d '[]')
    
    # main/develop에 머지된 브랜치인지 확인
    if git branch --merged develop 2>/dev/null | grep -q "$branch"; then
        echo "Removing merged worktree: $worktree_path ($branch)"
        git worktree remove "$worktree_path"
        git branch -d "$branch" 2>/dev/null
    fi
done

# 오래된 worktree 메타데이터 정리
git worktree prune

echo "✅ Cleanup complete!"
git worktree list

Claude Code 커스텀 명령어

<!-- .claude/commands/worktree-new.md -->
---
description: Create a new git worktree for parallel development
---

# Create New Worktree

Create a git worktree for: $ARGUMENTS

## Steps:
1. Parse the argument to determine type and name
   - Format: "feature user-auth" or "hotfix payment-bug main"
   
2. Run the worktree creation:
   ```bash
   ./scripts/new-worktree.sh <type> <name> [base]
  1. Navigate to the new worktree and set up:
  2. cd <worktree-path> npm install
  3. Copy necessary env files if they exist
  4. Report the worktree location and suggest next steps
```markdown
<!-- .claude/commands/worktree-status.md -->
---
description: Show status of all worktrees
---

# Worktree Status

Show the current status of all git worktrees:

```bash
echo "📊 All Worktrees:"
git worktree list

echo ""
echo "📋 Branch Status:"
for dir in ../worktrees/*/*; do
    if [ -d "$dir" ]; then
        echo "---"
        echo "📁 $dir"
        cd "$dir"
        git status --short
        echo "Last commit: $(git log -1 --format='%s (%cr)')"
        cd - > /dev/null
    fi
done
### Best Practices 체크리스트

**worktree 생성 시:**
- [ ] 프로젝트 밖에 worktree 디렉토리 생성 (`../worktrees/`)
- [ ] 의미 있는 디렉토리 구조 사용 (`feature/`, `bugfix/`, `hotfix/`)
- [ ] 브랜치 네이밍 규칙 따르기 (`feat/`, `fix/`, `hotfix/`)
- [ ] 올바른 base 브랜치 선택 (feature→develop, hotfix→main)
- [ ] `npm install` 또는 의존성 설치
- [ ] `.env` 파일 복사

**작업 중:**
- [ ] 각 worktree에서 `/init` 실행 (CLAUDE.md 생성)
- [ ] 세션 이름 명명 (`/session feature-user-auth`)
- [ ] 자주 커밋 (작은 단위로)
- [ ] tasks.md로 진행 상황 추적

**머지 시:**
- [ ] develop/main 최신화 후 리베이스
- [ ] 충돌 해결
- [ ] 테스트 통과 확인
- [ ] PR 생성 & 리뷰

**정리:**
- [ ] 머지 후 worktree 제거 (`git worktree remove`)
- [ ] 브랜치 삭제 (`git branch -d`)
- [ ] 주기적으로 `git worktree prune` 실행

### 병렬 개발 워크플로우

> "For instance, you might have one Claude refactoring your authentication system while another builds a completely unrelated data visualization component."
> — [Anthropic Best Practices](https://www.anthropic.com/engineering/claude-code-best-practices)

**예시: 3개 작업 동시 진행**

```bash
# 터미널 1: 인증 리팩토링
git worktree add ../auth-refactor -b refactor/auth
cd ../auth-refactor
claude
# "Refactor the authentication system to use JWT"

# 터미널 2: 새 기능 개발  
git worktree add ../ai-chat -b feat/ai-chat
cd ../ai-chat
claude
# "Implement AI chat feature with streaming"

# 터미널 3: 버그 수정
git worktree add ../hotfix -b fix/payment-bug
cd ../hotfix
claude
# "Fix the payment processing bug in checkout flow"

디렉토리 구조:

/projects/
├── my-project/        # 메인 (main 브랜치)
│   └── .git/          # 실제 Git 데이터
├── auth-refactor/     # worktree (refactor/auth 브랜치)
│   └── .git           # 링크 파일
├── ai-chat/           # worktree (feat/ai-chat 브랜치)
│   └── .git           # 링크 파일
└── hotfix/            # worktree (fix/payment-bug 브랜치)
    └── .git           # 링크 파일

/resume으로 세션 관리

"Sessions are stored per project directory. The /resume picker shows sessions from the same git repository, including worktrees." — Claude Code Docs

# worktree에서 세션 이름 지정
claude
> /session auth-refactoring-session

# 나중에 재개
claude --resume
# 또는 세션 내에서
> /resume

커스텀 명령어로 자동화

worktree 초기화 명령어:

<!-- .claude/commands/worktree-init.md -->
---
description: Initialize parallel worktrees for a feature
---

# Initialize Parallel Worktrees

## Variables
FEATURE_NAME: $ARGUMENTS

## Instructions

Create git worktrees for parallel development of FEATURE_NAME.

1. Create the worktrees directory if it doesn't exist:
   ```bash
   mkdir -p ../worktrees
  1. Create a new git worktree:
  2. git worktree add ../worktrees/FEATURE_NAME -b feat/FEATURE_NAME
  3. Copy environment files:
  4. cp .env.example ../worktrees/FEATURE_NAME/.env
  5. Install dependencies in the new worktree:
  6. cd ../worktrees/FEATURE_NAME && npm install
  7. Report the worktree location and next steps.
**사용:**
```bash
> /worktree-init user-dashboard

고급 패턴: 경쟁적 구현

같은 기능을 여러 방식으로 동시 구현하고 최적의 결과 선택:

# 3개의 다른 접근법으로 동시 구현
git worktree add ../impl-approach-1 -b feat/search-v1
git worktree add ../impl-approach-2 -b feat/search-v2  
git worktree add ../impl-approach-3 -b feat/search-v3

# 각 worktree에서 다른 지시
# Approach 1: "Implement search using Elasticsearch"
# Approach 2: "Implement search using PostgreSQL full-text"
# Approach 3: "Implement search using Algolia"

# 결과 비교 후 최적의 구현 선택

worktree 관리 팁

현재 worktree 목록:

git worktree list
# /projects/my-project        abc1234 [main]
# /projects/auth-refactor     def5678 [refactor/auth]
# /projects/ai-chat           ghi9012 [feat/ai-chat]

worktree 제거:

# 작업 완료 후
git worktree remove ../auth-refactor

# 강제 제거 (변경사항 있어도)
git worktree remove --force ../auth-refactor

오래된 worktree 정리:

git worktree prune

Part 3: devcontainer + git worktree 조합

최강 조합

devcontainer (환경 격리) + git worktree (작업 격리)
= 완벽한 병렬 개발 환경

워크플로우:

  1. 프로젝트를 devcontainer로 열기
  2. 컨테이너 안에서 git worktree 생성
  3. 각 worktree에서 별도 Claude 세션 실행
  4. YOLO 모드로 빠르게 작업
  5. 작업 완료 후 메인에 머지
# devcontainer 안에서
git worktree add ../feature-a -b feat/a
git worktree add ../feature-b -b feat/b

# 터미널 1
cd ../feature-a && claude --dangerously-skip-permissions

# 터미널 2  
cd ../feature-b && claude --dangerously-skip-permissions

CLAUDE.md에 병렬 개발 가이드 추가

# Parallel Development Guidelines

## Git Worktree Conventions
- Worktree location: `../worktrees/`
- Branch naming: `feat/`, `fix/`, `refactor/` prefixes
- Always run `/init` in new worktrees

## Session Management
- Name sessions descriptively: `/session feature-name-task`
- Use `/resume` to continue work

## Merge Protocol
1. Complete feature in worktree
2. Run all tests
3. Commit with semantic message
4. Switch to main and merge
5. Remove worktree after merge

주의사항

devcontainer 한계

  • IDE 통합 제한: 일부 IDE 기능이 작동 안 할 수 있음
  • 리소스 사용: Docker Desktop 메모리 8GB+ 권장
  • 초기 빌드 시간: 첫 빌드에 시간 소요
  • 신뢰할 수 있는 레포만: 악성 프로젝트는 여전히 위험

git worktree 한계

  • 파일 공유 불가: worktree 간 .env 등 복사 필요
  • node_modules: 각 worktree에서 npm install 필요
  • 머지 충돌: 결국 통합할 때 충돌 가능
  • 비용 증가: 여러 Claude 세션 = 더 많은 토큰 사용

언제 뭘 쓸까?

상황 추천

프로젝트별 환경 다름 devcontainer
YOLO 모드 안전하게 devcontainer
같은 레포 병렬 작업 git worktree
독립적 기능 동시 개발 git worktree
팀 환경 통일 devcontainer
빠른 실험/비교 git worktree

체크리스트

devcontainer 설정

  • [ ] VS Code Dev Containers 확장 설치
  • [ ] Docker Desktop 실행 중
  • [ ] .devcontainer/devcontainer.json 생성
  • [ ] Claude 설정 볼륨 마운트
  • [ ] 방화벽 규칙 확인 (필요시)

git worktree 활용

  • [ ] worktree 디렉토리 규칙 정하기 (../worktrees/)
  • [ ] 브랜치 네이밍 규칙 정하기
  • [ ] 각 worktree에서 /init 실행
  • [ ] 세션 이름 명명하기
  • [ ] 작업 완료 후 worktree 정리

병렬 개발

  • [ ] 독립적 작업인지 확인 (파일 충돌 없는지)
  • [ ] 각 Claude에 명확한 작업 지시
  • [ ] 주기적으로 진행 상황 확인
  • [ ] 머지 전 테스트 실행

마무리

**컨테이너 격리 (devcontainer)**는 프로젝트 간 환경 충돌을 막고, YOLO 모드를 안전하게 사용할 수 있게 해줘요.

git worktree는 같은 레포에서 여러 Claude 인스턴스를 동시에 돌릴 수 있게 해주는 공식 권장 방법이에요.

"Using git worktrees enables you to run multiple Claude sessions simultaneously on different parts of your project, each focused on its own independent task." — Anthropic Best Practices

둘을 조합하면 안전하고 효율적인 병렬 개발 환경을 구축할 수 있어요.

  • 환경 격리가 필요하면 → devcontainer
  • 작업 격리가 필요하면 → git worktree
  • 둘 다 필요하면 → devcontainer 안에서 git worktree

프로젝트 여러 개 동시에 진행하거나, 한 프로젝트에서 여러 기능을 병렬로 개발할 때 꼭 활용해보세요!


참고 자료

Anthropic 공식

커뮤니티 가이드

도구


 

반응형