Directory API 레퍼런스
이 문서는 Dagger API의 Directory 타입 레퍼런스예요. 워크스페이스 파일 읽기, 디렉터리 업로드 필터링(사전 호출/사후 호출 필터), 마운트, 디버깅 방법을 다뤄요.
출처: Dagger Docs
본문
워크스페이스 파일 읽기
모듈 안에서는 사용자의 프로젝트 디렉터리를 함수 인자로 받지 않아요. 대신 모듈의 생성자가 현재 워크스페이스에서 Dagger가 자동으로 채워 주는 Workspace를 받고, Workspace.directory(path)와 Workspace.file(path)로 디렉터리와 파일을 느리게(lazily) 읽어요. 함수가 실제로 사용하기 전엔 아무 것도 업로드되지 않아요. 정확한 문법은 SDK 가이드를 참고하세요.
필터
Dagger Function에 디렉터리를 인자로 넘기면 Dagger는 그 디렉터리 트리의 모든 것을 Dagger Engine으로 업로드해요. 큰 모노레포나 큰 파일이 들어 있는 디렉터리에서는 파일시스템 내용이 전송되는 동안 Dagger Function이 눈에 띄게 느려질 수 있어요. Dagger는 이 문제를 완화하려고 업로드할 파일과 디렉터리를 제어하는 필터를 제공해요.
Dagger는 이 문제를 완화하고 디렉터리 처리 방식을 최적화하려고 사전 호출(pre-call) 필터링과 사후 호출(post-call) 필터링을 제공해요.
필터링은 세 가지 방식으로 Dagger Function 성능을 개선해요:
- 호스트에서 Dagger Engine으로 전송되는 파일 크기를 줄여서 업로드 단계가 더 빨리 끝나요.
- 소스 디렉터리의 사소하고 무관한 변경이 Dagger 빌드 캐시를 무효화하지 않게 해줘요.
- 모노레포에서 컴포넌트/기능/서비스별 워크플로를 구성하는 것 같은 다양한 사용 사례를 가능하게 해요.
Dagger는 이미 캐싱으로 파일 업로드를 최적화한다는 점도 짚고 넘어갈게요. 이후 Dagger Function 호출은 앞선 호출 이후 바뀐 파일만 업로드해요. 필터링은 그 위에 성능을 더 개선할 수 있는 추가 최적화예요.
사전 호출 필터링 (Pre-call filtering)
사전 호출 필터링은 디렉터리가 Dagger Engine 컨테이너로 업로드되기 전에 걸러지는 거예요. 유용한 경우:
-
큰 모노레포. 보통 Dagger Function은 모노레포의 일부, 즉 특정 컴포넌트나 기능만 다뤄요. 워크트리 전체를 업로드하면 감당하기 어려운 비용이 들어요.
-
오디오/비디오 파일과 기타 바이너리 콘텐츠 같은 큰 파일. 업로드에 시간이 걸려요. 직접 관련이 없다면 보통 Dagger Function이 무시하게 두는 게 좋아요.
:::tip
.git 디렉터리는 두 경우 모두에 해당하는 좋은 예시예요. 대용량 바이너리 객체를 포함해 많은 데이터를 담고 있고, 버전 히스토리가 긴 프로젝트에서는 실제 소스 코드보다 커질 때도 있어요.
:::
- 의존성. 로컬에서 개발하면 보통 프로젝트 의존성도 로컬에 설치돼 있어요.
node_modules(Node.js),.venv(Python),vendor(PHP) 같은 것들이요. 로컬에서 Dagger Function을 호출하면 Dagger가 설치된 의존성까지 전부 업로드해요. 이건 나쁜 관행이자 비효율적이에요. 보통 Dagger Function이 로컬 설치 의존성은 무시하고 프로젝트 소스 코드만 다루길 원할 거예요.
:::note
Dagger Function은 호스트 파일시스템을 알지 못하기 때문에 기존 .dockerignore나 .gitignore 파일에서 제외 패턴을 자동으로 읽을 수 없어요. 같은 패턴을 Dagger Function에 직접 구현해야 해요. 이 글을 쓰는 시점에 Dagger는 기존 .dockerignore/.gitignore 파일에서 제외 패턴을 읽지 않아요(https://github.com/dagger/dagger/issues/6627). 이미 이런 파일을 쓰고 있다면 같은 패턴을 Dagger Function에 직접 구현해야 해요.
:::
Dagger Function에 사전 호출 필터를 구현하려면 Directory 인자에 ignore 파라미터를 추가하세요. ignore 파라미터는 .gitignore 문법을 따라요. 기억할 중요한 점:
- 인자 순서가 의미 있어요.
"**", "!**"패턴은 모든 것을 포함하고,"!**", "**"은 모든 것을 제외해요. - 경로 앞에
!를 붙이면 이전 ignore를 뒤집어요."!foo"는 이전에 무시한 게 없어서 효과가 없고,"**", "!foo"는foo를 제외한 모든 것을 제외해요.
Go — 지정된 디렉터리에서 Go 소스 코드 파일을 제외한 모든 것을 걸러내는 Dagger Function 예시예요:
Python — 지정된 디렉터리에서 Python 소스 코드 파일을 제외한 모든 것을 걸러내는 Dagger Function 예시예요:
TypeScript — 지정된 디렉터리에서 TypeScript 소스 코드 파일을 제외한 모든 것을 걸러내는 Dagger Function 예시예요:
PHP — 지정된 디렉터리에서 PHP 소스 코드 파일을 제외한 모든 것을 걸러내는 Dagger Function 예시예요:
Java — 지정된 디렉터리에서 Java 소스 코드 파일을 제외한 모든 것을 걸러내는 Dagger Function 예시예요:
쓸모 있는 패턴 예시 몇 가지예요:
Go
// exclude Go tests and test data
// +ignore=["**_test.go", "**/testdata/**"]
// exclude binaries
// +ignore=["bin"]
// exclude Python dependencies
// +ignore=["**/.venv", "**/__pycache__"]
// exclude Node.js dependencies
// +ignore=["**/node_modules"]
// exclude Git metadata
// +ignore=[".git", "**/.gitignore"]
여러 줄로 나눌 수도 있어요:
// +ignore=[
// "**_test.go",
// "**/testdata/**"
// ]
Python
# exclude Pytest tests and test data
Ignore(["tests/", ".pytest_cache"])
# exclude binaries
Ignore(["bin"])
# exclude Python dependencies
Ignore(["**/.venv", "**/__pycache__"])
# exclude Node.js dependencies
Ignore(["**/node_modules"])
# exclude Git metadata
Ignore([".git", "**/.gitignore"])
TypeScript
// exclude Mocha tests
@argument({ ignore: ["**.spec.ts"] })
// exclude binaries
@argument({ ignore: ["bin"] })
// exclude Python dependencies
@argument({ ignore: ["**/.venv", "**/__pycache__"] })
// exclude Node.js dependencies
@argument({ ignore: ["**/node_modules"] })
// exclude Git metadata
@argument({ ignore: [".git", "**/.gitignore"] })
PHP
// exclude PHPUnit tests and test data
#[Ignore('tests/', '.phpunit.cache', '.phpunit.result.cache')]
// exclude binaries #[Ignore('bin')]
// exclude Composer dependencies #[Ignore('vendor/')]
// exclude Node.js dependencies #[Ignore('**/node_modules')]
// exclude Git metadata #[Ignore('.git/', '**/.gitignore')]
Java
// exclude Java tests and test data
@Ignore({"src/test"})
// exclude binaries
@Ignore({"bin"})
// exclude Python dependencies
@Ignore({"**/.venv", "**/__pycache__"})
// exclude Node.js dependencies
@Ignore({"**/node_modules"})
// exclude Git metadata
@Ignore({".git", "**/.gitignore"})
사후 호출 필터링 (Post-call filtering)
사후 호출 필터링은 디렉터리가 Dagger Engine으로 업로드된 후에 걸러지는 거예요.
Dagger Function이 디렉터리를 "제자리에서" 수정할 때 유용해요. 애플리케이션을 빌드할 때 Dagger Function이 빌드 중에 소스 디렉터리에 새 파일을 추가하는 식으로 디렉터리를 바꿀 수 있어요. 사후 호출 필터를 쓰면 그 디렉터리를 다른 작업에 활용할 때 새 파일만 가져오고 오래된 파일은 무시하게 할 수 있어요.
좋은 예가 멀티 스테이지 빌드예요. 소스를 읽어 애플리케이션을 빌드하고 컴파일된 바이너리를 새 하위 디렉터리에 두는 Dagger Function(스테이지 1)을 상상해 보세요. 배포용 최종 컨테이너 이미지로 전부 전송하는 대신(스테이지 2), 사후 호출 필터로 컴파일된 파일만 전송할 수 있어요.
Go — Dagger Function에 사후 호출 필터를 구현하려면 Directory 객체에 Include와 Exclude 패턴을 지원하는 DirectoryWithDirectoryOpts 또는 ContainerWithDirectoryOpts 구조체를 쓰세요. 예시예요:
Python — Dagger Function에 사후 호출 필터를 구현하려면 Directory 객체를 다룰 때 include와 exclude 파라미터를 쓰세요. 예시예요:
TypeScript — Dagger Function에 사후 호출 필터를 구현하려면 Directory 객체를 다룰 때 include와 exclude 파라미터를 쓰세요. 예시예요:
PHP — Dagger Function에 사후 호출 필터를 구현하려면 Directory 객체를 다룰 때 include와 exclude 파라미터를 쓰세요. 예시예요:
Java — Dagger Function에 사후 호출 필터를 구현하려면 Directory 객체를 다룰 때 withInclude와 withExclude 함수를 지원하는 Container.WithDirectoryArguments 클래스를 쓰세요. 예시예요:
쓸모 있는 패턴 예시 몇 가지예요:
Go
// exclude all Markdown files
dirOpts := dagger.ContainerWithDirectoryOpts{
Exclude: "*.md*",
}
// include only the build output directory
dirOpts := dagger.ContainerWithDirectoryOpts{
Include: "build",
}
// include only ZIP files
dirOpts := dagger.DirectoryWithDirectoryOpts{
Include: "\*.zip",
}
// exclude Git metadata
dirOpts := dagger.DirectoryWithDirectoryOpts{
Exclude: "\*.git",
}
Python
# exclude all Markdown files
dir_opts = {"exclude": ["*.md*"]}
# include only the build output directory
dir_opts = {"include": ["build"]}
# include only ZIP files
dir_opts = {"include": ["*.zip"]}
# exclude Git metadata
dir_opts = {"exclude": ["*.git"]}
TypeScript
// exclude all Markdown files
const dirOpts = { exclude: ["*.md*"] }
// include only the build output directory
const dirOpts = { include: ["build"] }
// include only ZIP files
const dirOpts = { include: ["*.zip"] }
// exclude Git metadata
const dirOpts = { exclude: ["*.git"] }
PHP
// exclude all Markdown files
$dirOpts = ['exclude' => ['*.md*']];
// include only the build output directory
$dirOpts = ['include' => ['build']];
// include only ZIP files
$dirOpts = ['include' => ['*.zip']];
// exclude Git metadata
$dirOpts = ['exclude' => ['*.git']];
Java
// exclude all Markdown files
var dirOpts = new Container.WithDirectoryArguments()
.withExclude(List.of("*.md*"));
// include only the build output directory
var dirOpts = new Container.WithDirectoryArguments()
.withInclude(List.of("build"));
// include only ZIP files
var dirOpts = new Container.WithDirectoryArguments()
.withInclude(List.of("*.zip"));
// exclude Git metadata
var dirOpts = new Container.WithDirectoryArguments()
.withExclude(List.of("*.git"));
마운트
디렉터리와 파일을 다룰 때 Dagger Function이 만드는 컨테이너에 복사할지 마운트할지 선택할 수 있어요. Dagger API는 다음 메서드를 제공해요:
Container.withDirectory()는 컨테이너에 지정 경로에 디렉터리를 쓴 결과를 반환해요Container.withFile()은 컨테이너에 지정 경로에 파일을 쓴 결과를 반환해요Container.withMountedDirectory()는 컨테이너에 지정 경로에 디렉터리를 마운트한 결과를 반환해요Container.withMountedFile()은 컨테이너에 지정 경로에 파일을 마운트한 결과를 반환해요
마운트는 워크플로 실행 동안에만 효과가 있고, 최종 이미지에 복사되거나 포함되지 않아요. 게다가 마운트된 파일/디렉터리에 대한 변경은 대상 디렉터리에만 반영되고 마운트 소스에는 반영되지 않아요.
:::tip 최종 이미지 크기에 도움이 되는 것 외에도 마운트가 성능과 자원 효율이 더 좋아요. 경험상 가능하면 항상 마운트를 쓰는 게 좋아요. :::
디버깅
로그 사용하기
Dagger Cloud와 Dagger TUI 모두 디렉터리 업로드를 필터링하는 데 쓴 패턴에 대한 자세한 정보를 제공해요. TUI 로그나 Trace에서 업로드 스텝을 찾아 보세요:


디렉터리 내용 살펴보기
디렉터리 필터링을 디버깅하는 또 다른 방법은 Directory를 입력으로 받아 같은 Directory를 반환하는 함수를 만드는 거예요:
Go
func (m *MyModule) Debug(
ctx context.Context,
// +ignore=["*", "!analytics"]
source *dagger.Directory,
) *dagger.Directory {
return source
}
Python
@function
async def foo(
self,
source: Annotated[
dagger.Directory, Ignore(["*", "!analytics"])
],
) -> dagger.Directory:
return source
TypeScript
@func()
debug(
@argument({ ignore: ["*", "!analytics"] }) source: Directory,
): Directory {
return source
}
PHP
#[DaggerFunction]
public function debug(
#[Ignore('*'/, '!analytics')]
Directory $source,
): Directory {
return $source;
}
Java
@Function
public Directory debug(@Ignore({"*", "!analytics"}) Directory source) {
return source;
}
함수를 호출하면 디렉터리의 digest와 최상위 엔트리가 보여요. digest는 내용 기반이라 디렉터리 내용이 바뀌면 같이 바뀌고, entries 필드를 보면 끼어든 파일을 발견할 수 있을 거예요.
인터랙티브 터미널에서 디렉터리를 열어 파일시스템을 살펴볼 수도 있어요.
필터링된 디렉터리를 호스트로 내보내서 로컬 도구로 확인할 수도 있어요.
API 레퍼런스
전체 Directory 타입 API 표는 원문 페이지의 API reference 섹션에서 확인할 수 있어요.