在 Docker 容器中将 /dev/sda1 挂载到 /etc/hosts 是什么意思

What is the meaning of mounting /dev/sda1 to /etc/hosts in Docker container

我 运行 一个简单的 docker 容器 sudo docker run -it ubuntu:latest /bin/bash

当我检查挂载的文件系统时,使用:df -h,一个

Filesystem      Size  Used Avail Use% Mounted on
overlay          63G  4.3G   56G   8% /
tmpfs            64M     0   64M   0% /dev
tmpfs          1000M     0 1000M   0% /sys/fs/cgroup
/dev/sda1        63G  4.3G   56G   8% /etc/hosts
....

我无法理解最后一行,即 /dev/sda1 -> /etc/hosts,当我在主机上 运行 df -h 时,我得到挂载 /dev/sda1 -> /.

所以/dev/sda1实际上是我的硬盘,为什么它挂载到容器上的/etc/hosts,容器上的/etc/hosts怎么是一个内容正确的文件。

对这里发生的事情有任何解释吗?这是如何工作的?

你的post中有两个问题,让我按顺序回答。

1) 为什么/etc/{hosts,hostname,resolv.conf}文件是从外部挂载的?

我至少看到一个原因。

想象一下,如果容器引擎只是将这些文件写入容器的文件系统 并且 用户决定将 /etc 安装为卷(即完全合法且非常有用 - 安装 /etc 将允许用户在 docker run 的一个 -v 参数中为容器提供多个配置文件:

  • 首先,将卷挂载到容器的 /etc 目录;
  • 然后容器引擎更改其内容(写入 /etc 中的特定文件)。

启动此容器后,用户尝试再启动一个具有相同 /etc 卷的容器(同样,这是完全合法且有用的 - 例如,用户扩展某些服务并在 /etc 在实例中),并且...第二个容器覆盖卷上的 hostnamehostsresolv.conf 文件,影响第一个容器。

现在考虑当使用 bind-mounting 而不是直接写入时会发生什么:

  • 卷已挂载到容器的 /etc 目录;
  • 容器引擎 bind-mounts /etc/{hosts,hostname,resolv.conf} 从主机某处到容器的文件系统;
  • bind-mounts 隐藏 卷上这些文件的原始版本(如果有的话),从而保证卷上的文件在更新期间不会被修改容器设置,不会传播到其他容器。

2) 为什么我将 /dev/sda1 视为这些坐骑的来源?

检查 findmnt(8) 而不是 df(1):

$ docker run -it ubuntu
root@5a8ab4d6e716:/# findmnt
TARGET                           SOURCE
...
|-/etc/resolv.conf               /dev/sda1[/var/lib/docker/containers/5a8ab4d6e71691f279cbbcf5a295b5fa90fd138f10418c996ad7ea4440452816/resolv.conf]
|-/etc/hostname                  /dev/sda1[/var/lib/docker/containers/5a8ab4d6e71691f279cbbcf5a295b5fa90fd138f10418c996ad7ea4440452816/hostname]
`-/etc/hosts                     /dev/sda1[/var/lib/docker/containers/5a8ab4d6e71691f279cbbcf5a295b5fa90fd138f10418c996ad7ea4440452816/hosts]

实际上,这里的每一行输出显示三个字段(挂载目标/etc/hosts、挂载源/dev/sda1和FS根目录/var/lib/<...>/hosts) , 第三个没有显示 df(1).

根据关于 /proc/PID/mountinfo 文件的 man procfs 段落(这是有关实用程序安装的信息来源):

(4)  root: the pathname of the directory in the filesystem which forms the root of this mount.
(5)  mount point: the pathname of the mount point relative to the process's root directory.
...
(10) mount source: filesystem-specific information or "none".

对于大多数挂载,FS 根目录是 /(因为您挂载了整个文件系统),因此当您查看 df(1) 输出时不会丢失太多信息。但是,bind-mounts 个特定文件并非如此。