Dockerfile如何添加localhost别名

标签 docker

Dockerfile如何添加localhost别名?

您好,我需要在 Dockerfile 中添加 localhost 别名 我执行以下操作:

运行 echo '127.0.0.1 locdev' >>/etc/hosts

但是当我然后转到图像 bash 控制台时

$ docker exec -it my-image bash

并尝试 ping 确实抛出错误的主机

$ ping locdev
ping: unknown host

/etc/hosts 包含什么?

$ cat /etc/hosts
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.4  62a5e2d10730

没有其他记录

有谁知道我该怎么做?我需要在 Dockerfile 中执行此操作,因为外部服务运行此 docker 而我不从命令行运行它。

在我的例子中,它是一个 PHP 应用程序,保存在 Bitbucket 存储库中。有一个名为 PIPELINES 的新功能。它在 Docker 镜像上运行应用程序构建。

在我的情况下,这个应用程序连接到我无法更改配置的 mysql 服务器(它会中断生产)。在那个 docker 镜像上,我已经设置了 mysql 服务器。所以 localhost 可以工作,但我需要为 localhost 添加这个别名,以免破坏生产服务器;

Dockerfile 片段:

RUN \
 aliases="127.0.0.1 localhost locdev" &&\
 sed "1s/.*/$aliases/" /etc/hosts
RUN cat /etc/hosts

我的 docker build 输出示例:

Step 10 : RUN aliases="127.0.0.1 localhost locdev" && sed "1s/.*/$aliases/" /etc/hosts
 ---> Running in 11ac105d632d
127.0.0.1 localhost locdev
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2      383850eeb47b
 ---> 0248977e48bd
Removing intermediate container 11ac105d632d
Step 11 : RUN cat /etc/hosts
 ---> Running in 20fc2f40b5a9
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2      383850eeb47b
 ---> c9e47ee296c5
Removing intermediate container 20fc2f40b5a9
Successfully built c9e47ee296c5

最佳答案

因为 Docker 为您管理 /etc/hosts 文件,所以对 /etc/hosts 进行更改是行不通的。

但是,您可以在运行 docker createdocker run--add-host 选项将其他主机添加到 Docker 的 DNS 服务发现.

这是来自 docker run --help 的输出:

  --add-host value              Add a custom host-to-IP mapping (host:ip) (default [])

但请记住,来自容器内部的 127.0.0.1 不会将您带到容器主机,但会将您带到容器上,因为它有自己的 127.0.0.1 接口(interface)。

您的 docker 主机的 eth0 IP 地址可从您的容器内部路由。您可以在 --add-host 参数中使用它。例如,如果我的 Docker 主机是本地网络上的 192.168.1.43,我可以执行 docker run --add-host locdev:192.168.1.43 ...。此时,locdev 将从容器内部解析回该 ip。

关于Dockerfile如何添加localhost别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40004055/

相关文章:

bash - Docker 容器中的 pg_dump

git - 如何让 docker-compose 从远程 git 存储库构建图像?

docker - 在Openshift Online上安装Discourse(Docker镜像)

linux - 管道输出到命令和终端

docker - 无法在 docker 容器中运行的远程 Jupyter 服务器上保存文件

python - 我无法从容器外部访问 docker

docker - 容器运行后如何将容器目录挂载到另一个目录中?

php - CentOS 7.x 上 Laravel : PHP 7. x 的 Docker 容器

php - 包 "pecl.php.net/imagick"没有可用的版本。 OpenSSL 错误?

php - 为什么将 docker-compose exec 的输出管道输出到 grep,会破坏它?