如何从 docker 容器访问 Host 机器的 localhost 127.0.0.1

How to access the Host's machine's localhost 127.0.0.1 from docker container

我在本地主机上托管了 Git 守护程序,即 '/usr/bin/git daemon --listen=127.0.0.1 --base-path=/opt' 作为 systemd 服务,我正在尝试从 docker 容器访问它。我没有提到端口,因为我不想将端口暴露给外部网络。

Docker文件:

RUN git clone git://127.0.0.1/repo/ repo_dir

但它不起作用,它看起来像是在容器内部,它正在尝试连接容器的本地主机。

那么如何从 Docker 容器连接主机的本地主机?

its not working, its looks like inside container its trying to connect localhost of container.

是的,这就是容器提供的隔离背后的所有想法,甚至 docker build(每个 Dockerfile 行构建一个容器,并在中间图像中提交它)。

正如 OP dhairya, and mentioned in the documentation I referred in my comments: "Docker container networking" and docker build 评论的那样,您可以在构建期间为 RUN 指令设置 host 网络模式:然后 localhost将引用主机 localhost。

 docker build --network="host"

这是自 API 1.25+ only, in docker v.1.13.0-rc5(2017 年 1 月)

POST /build accepts networkmode parameter to specify network used during build.


但是如果你在实际构建的镜像中不需要Git(其主要过程运行),那么

会更容易
  • 在本地克隆 repo(直接在主机上) docker 构建之前。
    您需要将它克隆到 Dockerfile 所在的位置,因为它必须相对于正在构建的源目录(构建的上下文)。
  • 在 Dockerfile 中使用 COPY directive,复制表示检出 Git 存储库的主机文件夹。
    注意:将 .git/: 添加到您的 .dockerignore(与您的 Dockerfile 位于同一文件夹中的文件),以便 而不是 复制 repo_dir/.git 文件夹如果你的目标图像中没有 git,那么克隆的 repo。

    COPY repo_dir .
    

(这里'.'表示正在构建的镜像中的当前WORKDIR