如何将我容器的主机名添加到 /etc/hosts?

How to add my container's hostname to /etc/hosts?

为了支持一些旧的软件解决方案,我需要将我的容器的 hostname 绑定到 127.0.0.1,留下这样的东西:

$ hostname
4e84a7ae5f92
$ cat /etc/hosts | grep 127.0.0.1
127.0.0.1       localhost 4e84a7ae5f92

最好的情况是在 Dockerfile 中执行,但由于 docker build 构建的是映像(而不是容器),这似乎不现实。
另外,如果我尝试在 运行 容器中使用 sed 来执行此操作,我最终会遇到错误:

$ sed -i '/^127\.0\.0\.1.*/ s/$/ '$(hostname)'/' /etc/hosts
sed: cannot rename /etc/sedC5PkA2: Device or resource busy

我能做什么?

docker run 命令有一个名为 --hostname="" 的选项,它负责处理您的 /etc/hostname 文件。

/etc/hosts 文件中的主机到 IP 映射可以使用选项 --add-host=[] 然后管理。

将容器名称添加到 /etc/hosts 的正确方法是使用标志 --add-host。在您的情况下,假设您想要在分离模式下使用图像 <image-name> 创建并启动一个名为 <container-name> 的新容器:

docker run --name <container-name> --add-host <container-name>:127.0.0.1 -d <image-name>`

这将创建以下 /etc/hosts(请注意最后一行):

127.0.0.1       localhost
127.0.0.1       4e84a7ae5f92

已使用 Docker 1.12.0-rc2 进行测试。