Dagger TypeScript 客户端 ContainerWithMountedTempOpts 详解:在容器中挂载临时目录

原创2026-09-16 14:07:102,000 阅读
文章标签:CI/CD云原生容器编排容器运行时DevOps可观测性CLI工作流自动化后端GraphQL构建工具认证鉴权

Dagger TypeScript 客户端 ContainerWithMountedTempOpts 详解:在容器中挂载临时目录

导读

本文围绕 Dagger 官方 TypeScript SDK 自动生成的 API 类型 ContainerWithMountedTempOpts 展开,讲解 Container.withMountedTemp() 的完整语义:如何在容器内挂载一块仅存在于单次 withExec 调用生命周期内的临时目录(tmpfs),以及如何通过 size 与 expand 两个可选参数控制容量和环境变量展开。读者将掌握该 API 的 TypeScript 调用方式、底层引擎实现原理(源码在 core/schema/container.go),以及验证其行为的最小测试示例。

一、ContainerWithMountedTempOpts 类型定义

该类型别名定义于 Dagger 官方 TypeScript SDK 自动生成的 API 客户端中,文档源文件位于 docs/versioned_docs/version-0.20/reference/typescript/api/client.gen/type-aliases/ContainerWithMountedTempOpts.md,对应的自动生成源码位于 sdk/typescript/src/api/client.gen.ts。

ContainerWithMountedTempOpts = object

它不是一个类,而是一个纯配置对象的类型别名,作为 Container.withMountedTemp(path, opts?) 的第二个可选参数传入。其全部属性均为可选,共两个字段,如下表所示:

属性 类型 是否必填 说明
expand boolean 可选 是否根据容器内当前环境变量,对 path 中的 ${VAR} 或 $VAR 进行替换(例如 "/$VAR/foo")
size number 可选 临时目录的容量大小,单位为字节

二、withMountedTemp 的语义:一次 withExec 的临时挂载

在展开参数之前,需要先理解这个方法本身的定位。在 sdk/typescript/src/api/client.gen.ts 中,方法签名带有一段关键的 JSDoc 注释:

Retrieves this container plus a temporary directory mounted at the given path. Any writes will be ephemeral to a single withExec call; they will not be persisted to subsequent withExecs.

这解释了临时目录的本质:

  • 它会在指定路径挂载一块 tmpfs(内存文件系统),容器内任何进程对它的写入都不会落到镜像层或持久卷中;
  • 写入内容只在紧接着的一次 withExec 调用中可见,之后的 withExec 将看不到这些数据(除非重新写入);
  • 因此它非常适合存放进程间通信用的中间文件、一次性临时数据、不希望泄漏到最终镜像的敏感中间产物等场景。

这一点与 withMountedVolume(持久卷)和 withMountedDirectory(宿主机/上游目录)形成鲜明对比:后两者是持久化的,而临时目录天然是易失的。

TypeScript 调用形态

import { connect } from "@dagger.io/dagger";

connect(async (client) => {
  const ctr = client
    .container()
    .from("alpine:latest")
    // 在 /mnt/tmp 挂载一块 4KB 的临时目录
    .withMountedTemp("/mnt/tmp", { size: 4000 })
    .withExec(["sh", "-c", "echo hello > /mnt/tmp/msg && cat /mnt/tmp/msg"]);

  const out = await ctr.stdout();
  console.log(out); // hello
});

三、size:控制临时目录容量

size 是可选属性,类型为 number,单位是字节,用于指定 tmpfs 挂载的大小上限。不传时使用引擎/内核的默认值(无显式 size 限制)。

在引擎侧,这个参数的定义位于 core/schema/container.go:

type containerWithMountedTempArgs struct {
	Path   string
	Size   dagql.Optional[dagql.Int]
	Expand bool `default:"false"`
}

可以看到 Size 是 dagql.Optional<a href="https://link.gitcode.com/i/9ceaa984a0a67771744c589025556558" target="_blank">dagql.Int],也就是说它天然允许“未提供”的状态。挂载时,size 会写入 tmpfs 的底层描述结构 [TmpfsMountSource:

type TmpfsMountSource struct {
	// Configure the size of the mounted tmpfs in bytes.
	Size int
}

并在 withMountedTemp 的实现中,通过 core.ContainerMount 的 TmpfsMountSource 字段把该临时目录挂载到目标路径。由于传入的是 Optional 值,未指定 size 时挂载的就是“无大小上限”的默认 tmpfs。

注意单位:size 的单位是字节,例如 size: 4 * 1024 * 1024 表示 4MB,不要直接按 KB/MB 数值传入,否则会得到远超预期的容量。

测试验证

仓库的集成测试 core/integration/container_test.go 直接验证了 size 的行为。测试通过在容器内执行 grep /mnt/tmp /proc/mounts 来观察挂载的实际参数:

  • 默认(不传 size)时,输出包含 tmpfs /mnt/tmp tmpfs,且不包含 size 关键字,说明未施加显式大小限制;
  • 传入 {Size: 4000} 时,输出包含 size=4k,说明引擎把 4000 字节的请求下发到了 tmpfs 挂载参数中。
t.Run("default", func(ctx context.Context, t *testctx.T) {
	output, err := output([]dagger.ContainerWithMountedTempOpts{})
	require.NoError(t, err)
	require.Contains(t, output, "tmpfs /mnt/tmp tmpfs")
	require.NotContains(t, output, "size")
})

t.Run("sized", func(ctx context.Context, t *testctx.T) {
	output, err := output([]dagger.ContainerWithMountedTempOpts{
		{Size: 4000},
	})
	require.NoError(t, err)
	require.Contains(t, output, "size=4k")
})

四、expand:按容器环境变量展开挂载路径

expand 是另一个可选属性,类型为 boolean,默认值为 false。当其为 true 时,引擎会用容器当前定义的环境变量对 path 中的 "${VAR}" 或 "$VAR" 占位符做替换。例如容器内已设置环境变量 FOO=/data,则 path 传入 "/$FOO/cache" 时会解析为 /data/cache。

在引擎侧的默认值通过 default:"false" 标签声明(见上文 containerWithMountedTempArgs 结构体),也就是说:

  • 不传 expand 或传 false:path 按字面值使用,$ 不会被展开;
  • 传 true:path 中的环境变量引用会被容器当前环境变量替换。

其展开逻辑实现在 expandEnvVar 函数中,核心行为如下:

func expandEnvVar(ctx context.Context, parent *core.Container, input string, expand bool) (string, error) {
	if !expand {
		return input, nil
	}
	cfg, err := parent.ImageConfig(ctx)
	if err != nil {
		return "", err
	}
	...
	expanded := os.Expand(input, func(k string) string {
		// set error if its a secret env variable
		if slices.Contains(secretEnvs, k) {
			secretEnvFoundError = fmt.Errorf("expand cannot be used with secret env variable %q", k)
			return ""
		}
		if slices.Contains(volatileEnvs, k) {
			volatileEnvFoundError = fmt.Errorf("expand cannot be used with volatile env variable %q", k)
			return ""
		}
		...
	})
	...
}

从源码可以推断出几个关键约束:

  • 展开使用 Go 的 os.Expand,因此同时支持 ${VAR} 与 $VAR 两种写法;
  • 环境变量的来源是容器自身的环境配置(镜像配置中的 Env,以及通过 withEnvVariable 等 API 设置的变量);
  • 若 path 中引用了由 Secret 注入的环境变量(secret env)或易变环境变量(volatile env),展开会直接报错并拒绝执行。这是引擎刻意为之的安全限制:secret/volatile 的值不应被反序列化并拼接到挂载路径中,防止敏感信息泄漏到查询/缓存层;
  • expand 需要读取镜像配置(parent.ImageConfig),这也是它与直接拼路径相比多出的一次间接开销。

用法示例

const ctr = client
  .container()
  .from("alpine:latest")
  .withEnvVariable("WORK_DIR", "/tmp/work")
  // expand 为 true,"/$WORK_DIR/cache" 会被解析为 "/tmp/work/cache"
  .withMountedTemp("/$WORK_DIR/cache", { expand: true });

注意:若容器内并未定义 WORK_DIR,展开后该占位符会被替换为空字符串,因此请确保引用的环境变量确实已通过镜像 ENV 或 withEnvVariable 设置。

五、底层实现:惰性状态与挂载链

从源码结构看,withMountedTemp 的挂载操作被建模为惰性状态(LazyState),这是 Dagger 容器操作的通用模式。在 core/container.go 中定义了对应的惰性结构:

type ContainerWithMountedTempLazy struct {
	LazyState
	Parent dagql.ObjectResult[*Container]
	Target string
	Size   int
}

其 Evaluate 方法(core/container.go)在真正需要物化容器时才执行挂载:

  • 先从 Parent 容器物化出完整状态(materializeContainerStateFromParent);
  • 再调用 container.WithMountedTemp(ctx, lazy.Target, lazy.Size) 施加 tmpfs 挂载;
  • 完成后清空 Lazy,使后续操作基于已物化的容器继续叠加。

同时,该惰性结构实现了 AttachDependencies 与 EncodePersisted(core/container.go),分别负责依赖图的附加和挂载状态的持久化编码。这意味着 withMountedTemp 挂载点可以被缓存系统序列化、恢复与复用,与其他挂载(withMountedVolume、withMountedSecret、withMountedDirectory 等)共享同一套挂载链模型(ContainerMounts)。

在挂载链层面,每次调用都会向 ctr.Mounts 追加一个携带 TmpfsMountSource 的挂载项(见 withMountedTemp),因此多次调用 withMountedTemp 会叠加多个临时目录挂载点,后续可通过 withoutMount 移除。

六、实践要点与使用建议

结合文档、源码与测试,使用 ContainerWithMountedTempOpts 时有几点值得注意:

  1. 生命周期意识:临时目录的内容只对紧接着的一次 withExec 可见。如果需要跨多次 withExec 共享,请改用 withMountedVolume(持久卷);如果需要向宿主机/上游目录回写,请改用 withMountedDirectory。
  2. 容量按需设置:默认 tmpfs 无显式大小限制(取决于引擎运行环境),但在追求确定性构建时建议显式传入 size(字节),避免不同环境下行为差异。测试表明 4000 字节会体现为 size=4k 的挂载参数。
  3. expand 与 Secret 互斥:expand: true 时路径中不能引用 secret/volatile 环境变量,否则引擎直接报错;这是安全设计,不应绕过。
  4. 路径解析:path 相对容器工作目录(WorkingDir)解析为绝对路径(withMountedTemp),建议直接使用绝对路径(如 /tmp/xxx)以避免歧义。
  5. 典型场景:临时目录非常适合构建管线中的中间产物隔离(如包管理器缓存目录、测试报告临时输出、进程间 socket 文件等),既保证单次执行的隔离性,又不会污染最终镜像。
登录后查看全文
dagger