--- outline: [2,4] --- # tmpfs 挂载 [Volumes](https://docs.docker.com/engine/storage/volumes/) 和 [绑定挂载](https://docs.docker.com/engine/storage/bind-mounts/)允许您在主机和容器之间共享文件,以便即使在容器停止后也可以保留数据。 如果您在 Linux 上运行 Docker,则还有第三个选项:tmpfs mounts。当您使用 tmpfs 挂载创建容器时,容器可以在容器的可写层之外创建文件。 与 volumes 和 bind 挂载相反,tmpfs 挂载是临时的,仅保留在主机内存中。当容器停止时,tmpfs 挂载将被删除,并且写入其中的文件不会被持久化。 tmpfs 挂载最适合用于不希望数据保留在主机上或容器内的情况。这可能是出于安全原因,或者是为了在应用程序需要写入大量非持久性状态数据时保护容器的性能。 :::danger 重要 tmpfs 挂载直接映射到 [tmpfs](https://en.wikipedia.org/wiki/Tmpfs) 的 Linux 内核。因此,临时数据可以写入交换文件,从而持久化到文件系统中。 ::: ## 挂载到现有数据上 如果在容器中存在文件或目录的目录中创建 tmpfs 挂载,则预先存在的文件将被挂载遮挡。 这类似于将文件保存到 Linux 主机上的 `/mnt` 中,然后将 USB 驱动器挂载到 `/mnt` 中。 `/mnt` 的内容将被 USB 驱动器的内容遮挡,直到卸载 USB 驱动器。 对于容器,没有直接的方法可以删除挂载以再次显示被遮挡的文件。最好的选择是重新创建没有挂载的容器。 ## tmpfs 挂载的限制 - 与卷和绑定挂载不同,您不能在容器之间共享 tmpfs 挂载。 - 仅当在 Linux 上运行 Docker 时,此功能才可用。 - 在 tmpfs 上设置权限可能会导致它们 [容器重启后重置](https://github.com/docker/for-linux/issues/138)。在某些情况下 [设置 UID/GID](https://github.com/docker/compose/issues/3425#issuecomment-423091370) 可以作为一种解决方法。 ## 语法 要使用 `docker run` 命令挂载 tmpfs,您可以使用 `--mount` 或 `--tmpfs` 标志。 ```bash docker run --mount type=tmpfs,dst= docker run --tmpfs ``` 通常,`--mount` 是首选。主要区别在于 `--mount` flag 更明确,并支持所有可用选项。 `--tmpfs` 标志不能用于 swarm 服务。您必须使用 `--mount`。 ### --mount 的选项 `--mount` 标志由多个键值对组成,用逗号分隔,每个键值对由一个 `=` 元组组成。键的顺序并不重要。 ```bash docker run --mount type=tmpfs,dst=[,=...] ``` `--mount type=tmpfs` 的有效选项包括: | 选项 | 描述 | | - | - | | `destination`, `dst`, `target` (目标) | tmpfs 挂载的大小(以字节为单位)。如果未设置,则 tmpfs 卷的默认最大大小为主机总 RAM 的 50%。 | | `tmpfs-size` (tmpfs 大小) | tmpfs 挂载的大小(以字节为单位)。如果未设置,则 tmpfs 卷的默认最大大小为主机总 RAM 的 50%。 | | `tmpfs-mode` (tmpfs 模式) | tmpfs 的文件模式(以八进制为单位)。例如,`700` 或 `0770`。默认为 `1777` 或 world-writable。 | ###### 例 ```bash docker run --mount type=tmpfs,dst=/app,tmpfs-size=21474836480,tmpfs-mode=1770 ``` ### --tmpfs 的选项 `--tmpfs` 标志不允许您指定任何选项。 ## 在容器中使用 tmpfs 挂载 要在容器中使用 `tmpfs` 挂载,请使用 `--tmpfs` 标志,或使用 `--mount` 标志与 `type=tmpfs` 和 `destination` 选项一起使用。 没有 `tmpfs` 挂载的源。以下示例在 `/app` 中。第一个示例使用 `--mount` 标志,第二个示例使用 `--tmpfs` 标志。 :::code-group ```bash [--mount] docker run -d \ -it \ --name tmptest \ --mount type=tmpfs,destination=/app \ nginx:latest ``` ```bash [--tmpfs] $ docker run -d \ -it \ --name tmptest \ --tmpfs /app \ nginx:latest ``` ::: 通过查看 `docker inspect` 输出的 `Mounts` 部分来验证挂载是否为 `tmpfs` 挂载: ```bash docker inspect tmptest --format '{{ json .Mounts }}' [{"Type":"tmpfs","Source":"","Destination":"/app","Mode":"","RW":true,"Propagation":""}] ``` 停止并移除容器: ```bash docker stop tmptest docker rm tmptest ``` ## 后续步骤 - 了解 [卷](/docs/storage/volumes)。 - 了解 [绑定挂载](/docs/storage/mount.md)。 - 了解 [存储驱动程序](/docs/storage/drivers/)。