如何将我的容器的主机名添加到/ etc / hosts?
为了支持一些旧的软件解决scheme,我需要绑定我的容器的hostname
到127.0.0.1
,留下我这样的东西:
$ hostname 4e84a7ae5f92 $ cat /etc/hosts | grep 127.0.0.1 127.0.0.1 localhost 4e84a7ae5f92
最好的情况是在Dockerfile中做,但是由于docker docker build
构build的是一个图像(而不是一个容器),所以看起来并不现实。
另外,如果我试图用正在运行的容器中的sed
来做到这一点,我最终会遇到一个错误:
$ sed -i '/^127\.0\.0\.1.*/ s/$/ '$(hostname)'/' /etc/hosts sed: cannot rename /etc/sedC5PkA2: Device or resource busy
我能做什么 ?
--hostname=""
run
命令有一个名为--hostname=""
的选项,用于处理/etc/hostname
文件。
/etc/hosts
文件中的host-to-ip映射可以使用--add-host=[]
选项进行pipe理。
将容器名称添加到/etc/hosts
的正确方法是使用标志--add-host
。 在你的情况下,假设你想要在分离模式下使用image <image-name>
创build并启动一个名为<container-name>
的新容器:
docker run --name <container-name> --add-host <container-name>:127.0.0.1 -d <image-name>`
这将创build以下/etc/hosts
(请注意最后一行):
127.0.0.1 localhost 127.0.0.1 4e84a7ae5f92
它已经使用Docker 1.12.0-rc2进行了testing。