Stay Hungry,Stay Foolish!

host.docker.internal

host.docker.internal

https://zhuanlan.zhihu.com/p/444263754

docker compose 里面的容器怎么访问主机自身起的服务呢?

20.10.0 版本在 linux 新增 host.docker.internal 支持docker run -it --add-host

=host.docker.internal:host-gateway alpine 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.1      host.docker.internal # --add-host的作用就是添加了这行到/etc/hosts
172.17.0.3      cb0565ceea26

相关提交

这个 add-host 的意思是告诉容器,容器对域名 host.docker.internal 的访问都将转发到 host-gateway 去。

也就是容器内部访问这个域名 host.docker.internal 时,就会访问到对应的主机上的 host-gateway 地址。

从而达到容器访问主机上服务的效果。

那么,这个 add-host 怎么用在 compose 上呢?

在 build 里使用 extra_hosts

version: "2.3" # 因为某个bug的存在,只能用version2,不能用version3
services:
  tmp:
    build:
      context: .
    extra_hosts: # 配置extra_hosts
      - "host:IP"
    command: -kIL https://host
    tty: true
    stdin_open: true

docker compose 配置中文说明

参照

测试:

docker-compose --version
docker-compose version
 1.29.2, build 5becea4c

新建一个服务,在主机上运行;

package main

import (
        "fmt"
        "net/http"
)

func main() {
        handler := http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
                fmt.Println("hi")
                resp.Write([]byte("hello"))
        })
        if err := http.ListenAndServe(":8080", handler); err != nil {
                panic(err)
        }
}

新建 compose,里面也起一个服务,这个服务需要访问上述的主机服务;

version: "2.3" # version改为3.3也可以
services:
  server:
    image: curlimages/curl
    command: curl http://host.docker.internal:8080
    extra_hosts:
      - "host.docker.internal:host-gateway"

在终端访问容器服务,容器服务访问主机服务,如果能正常执行,则表示完成。

执行docker-compose up,能看到请求成功。

 

如何检测docker是否支持host.docker.internal

https://juejin.cn/post/7409974426370244623

 

在容器化的世界里,Docker 扮演着至关重要的角色。而有时候,我们需要了解 Docker 是否支持 “host.docker.internal” 这一特殊的主机名,以便在容器中方便地访问宿主机的服务。

一、什么是 “host.docker.internal”

“host.docker.internal” 是一个特殊的主机名,它允许在 Docker 容器中访问宿主机的 IP 地址。这在开发和调试过程中非常有用,例如,当你需要在容器中访问宿主机上运行的数据库或其他服务时。

二、检测方法

  1. 使用 Ping 命令

    • 在容器中运行一个简单的命令,如ping host.docker.internal。如果能够成功解析并收到响应,说明 Docker 支持 “host.docker.internal”。
    • 例如,启动一个临时的容器并执行以下命令:


 

posted @ 2025-06-02 22:42  lightsong  阅读(275)  评论(0)    收藏  举报
千山鸟飞绝,万径人踪灭