【问题标题】:What is the meaning of mounting /dev/sda1 to /etc/hosts in Docker containerDocker容器中挂载/dev/sda1到/etc/hosts是什么意思
【发布时间】:2019-10-27 23:01:38
【问题描述】:

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

当我检查挂载的文件系统时,使用: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是一个内容正确的文件。

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

【问题讨论】:

  • 输出有点误导。只有hosts文件被挂载到容器中,因为docker需要控制它的内容。
  • @Henry 容器中的/etc/hosts文件不是从宿主机挂载的,是不同的文件
  • 没错,它是一个由 docker 控制的文件(很可能在 /var/lib/docker 下的某个地方)。不是docker主机的/etc/hosts。

标签: linux docker ubuntu mount hosts


【解决方案1】:

您的帖子中有两个问题,让我依次回答。

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

我至少看到了一个原因。

想象一下,如果容器引擎将这些文件简单地写入容器的文件系统并且用户会决定将/etc 挂载为卷(这是完全合法且非常有用的 - 挂载)会发生什么/etc 将允许用户在一个 -v 参数中为容器提供多个配置文件 docker run):

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

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

现在考虑当使用绑定挂载而不是直接写入时会发生什么:

  • 卷被挂载到容器的/etc目录;
  • 容器引擎将 /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]

其实这里每行输出显示三个字段(mount target /etc/hosts, mount source /dev/sda1 and FS root /var/lib/<...>/hosts),第三个没有被@987654342显示@。

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

(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) 输出时不会丢失太多信息。但是,对于特定文件的绑定挂载,情况并非如此。

【讨论】:

    猜你喜欢
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多